GridView禁用掉viewstate之后的新建,编辑,删除

示例程序为一个超级Mini的图书管理,DB中只有一个名为"tableBook"的表,里面也只有三个字段ID(autonumber),bookName,BookAuthor。效果图:

GridView禁用掉viewstate之后的新建,编辑,删除_第1张图片

GridView禁用掉viewstate之后的新建,编辑,删除_第2张图片

Main.aspx: 

<% @ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main"  %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml"   >
< head  runat ="server" >
    
< title > Untitled Page title >
    
    
< script  type ="text/javascript" >
    
        
//将当前行生成的文本框中的值存入相应的控件,并点击“修改”
        function Update(id)
        
{
            
if(confirm('确定要修改吗?'))
            
{
                document.getElementById(
'hiddenId').value = id;
                document.getElementById(
'hiddenName').value = document.getElementById('newName').value;
                document.getElementById(
'hiddenAuthor').value = document.getElementById('newAuthor').value;
                document.getElementById(
'bnUpdate').click();
            }

        }

        
        
//将当前行中的ID放入hiddenId并点击“删除”
        function Delete(id)
        
{
            
if(confirm('确定要删除吗?'))
            
{
                document.getElementById(
'hiddenId').value = id;
                document.getElementById(
'bnDelete').click();
            }

        }

        
        
//将当前行的RowIndx放入GVIndex并点击bnShowTextBox在当前行显示文本框
        function ShowTextBox(gvIndex)
        
{
            document.getElementById(
'GVIndex').value = gvIndex;
            document.getElementById(
'bnShowTextBox').click();
        }

        
        
//点击bnShowTextBox4New,显示用于创建的控件
        function ShowControl4New()
        
{
            document.getElementById(
'bnShowTextBox4New').click();
        }

        
        
//将新建数据暂存至控件并点击“创建”
        function CreateNew()
        
{
            
var newName = document.getElementById('createNewName').value;
            
var newAuthor = document.getElementById('createNewAuthor').value;
            
//检查是否为空
            if(newName == "" || newAuthor == "")
            
{
                alert(
'不可为空');
                
return;
            }

            document.getElementById(
'hiddenName').value = newName;
            document.getElementById(
'hiddenAuthor').value = newAuthor;
            document.getElementById(
'bnCreateNew').click();
        }


    
script >
head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
        
< table  width ="80%" >
            
< tr >
                
< td  align ="center" >
                 
< asp:GridView  ID ="gvBook"  runat ="server"  CellPadding ="4"  ForeColor ="#333333"  GridLines ="None"  OnRowDataBound ="gvBook_RowDataBound"  ShowFooter ="True"  EnableViewState ="False"  OnRowCreated ="gvBook_RowCreated" >
                    
< FooterStyle  BackColor ="#990000"  Font-Bold ="True"  ForeColor ="White"   />
                    
< RowStyle  BackColor ="#FFFBD6"  ForeColor ="#333333"   />
                    
< PagerStyle  BackColor ="#FFCC66"  ForeColor ="#333333"  HorizontalAlign ="Center"   />
                    
< SelectedRowStyle  BackColor ="#FFCC66"  Font-Bold ="True"  ForeColor ="Navy"   />
                    
< HeaderStyle  BackColor ="#990000"  Font-Bold ="True"  ForeColor ="White"   />
                    
< AlternatingRowStyle  BackColor ="White"   />
                     
< Columns >
                         
< asp:TemplateField  HeaderText ="操作" > asp:TemplateField >
                     
Columns >
                
asp:GridView >
                
td >
            
tr >
        
table >
    
div >
        
< input  id ="hiddenId"  style ="display:none"  type ="text"  runat ="server"   />
        
< input  id ="hiddenName"  style ="display:none"  type ="text"  runat ="server"   />
        
< input  id ="hiddenAuthor"  style ="display:none"  type ="text"  runat ="server"   />
        
< input  id ="GVIndex"  style ="display:none"  type ="text"  runat ="server"   />
        
< asp:Button  ID ="bnUpdate"  runat ="server"  style ="display:none"  Text ="Update"  OnClick ="bnUpdate_Click"   />
        
< asp:Button  ID ="bnShowTextBox"  runat ="server"  style ="display:none"  Text ="ShowTextBox"  OnClick ="bnShowTextBox_Click"   />
        
< asp:Button  ID ="bnShowTextBox4New"  runat ="server"  OnClick ="bnShowTextBox4New_Click"  Style ="display:none"  Text ="ShowTextBox4New"   />
        
< asp:Button  ID ="bnCreateNew"  runat ="server"  OnClick ="bnCreateNew_Click"  Style ="display:none"  Text ="CreateNew"   />
        
< asp:Button  ID ="bnDelete"  runat ="server"  OnClick ="bnDelete_Click"  Style ="display:none"  Text ="Delete"   />
    
form >
body >
html >

Main.aspx.cs:

using  System;
using  System.Data;
using  System.Configuration;
using  System.Collections;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

public   partial   class  Main : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        GVBind();
    }


    
/// 
    
/// 绑定GridView数据源
    
/// 

    protected void GVBind()
    
{
        
if (CBook.GetData() != null)
        
{
            gvBook.DataSource 
= CBook.GetData();
            gvBook.DataBind();
        }

    }


    
//向各行“操作”列写入“功能键”
    protected void gvBook_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
        
{
            e.Row.Cells[
0].Text = "新建  ";
            e.Row.Cells[
0].Text += "" + e.Row.RowIndex + ")'>修改  ";
            e.Row.Cells[
0].Text += "" + e.Row.Cells[1].Text + ")'>删除";
        }

    }


    
//显示用于修改的文本框
    protected void bnShowTextBox_Click(object sender, EventArgs e)
    
{
        
int index;
        
if (Int32.TryParse(GVIndex.Value, out index))
        
{
            gvBook.Rows[index].Cells[
2].Text = "" + gvBook.Rows[index].Cells[2].Text + "' />";
            gvBook.Rows[index].Cells[
3].Text = "" + gvBook.Rows[index].Cells[3].Text + "' />";
            gvBook.Rows[index].Cells[
0].Text = "" + gvBook.Rows[index].Cells[1].Text + ")'>确定";
        }

    }

    
    
//执行修改
    protected void bnUpdate_Click(object sender, EventArgs e)
    
{
        
try
        
{
            
int id;
            
if (Int32.TryParse(hiddenId.Value, out id) && hiddenName.Value != string.Empty && hiddenAuthor.Value != string.Empty)
            
{
                CBook.Update(id, hiddenName.Value, hiddenAuthor.Value);
                CBook.ShowMessage(
this"修改成功");
                GVBind();
            }

            
else
            
{
                CBook.ShowMessage(
this"输入有误,请检查");
            }

        }

        
catch (Exception ex)
        
{
            CBook.ShowMessage(
this, ex.Message);
        }

    }


    
//显示用于创建的文本框及按钮
    protected void bnShowTextBox4New_Click(object sender, EventArgs e)
    
{
        gvBook.FooterRow.Cells[
0].Text = "请输入新记录信息:";
        gvBook.FooterRow.Cells[
1].Text = "";
        gvBook.FooterRow.Cells[
2].Text = " ";
    }


    
//执行创建
    protected void bnCreateNew_Click(object sender, EventArgs e)
    
{
        
try
        
{
            CBook.Insert(hiddenName.Value, hiddenAuthor.Value);
            CBook.ShowMessage(
this"创建成功");
            GVBind();
        }

        
catch(Exception ex)
        
{
            CBook.ShowMessage(
this, ex.Message);
        }

    }


    
//执行删除
    protected void bnDelete_Click(object sender, EventArgs e)
    
{
        
try
        
{
            
int id;
            
if (Int32.TryParse(hiddenId.Value, out id))
            
{
                CBook.Delete(id);
                CBook.ShowMessage(
this"删除成功");
                GVBind();
            }

        }

        
catch (Exception ex)
        
{
            CBook.ShowMessage(
this, ex.Message);
        }

    }


    
//隐藏ID列
    protected void gvBook_RowCreated(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        
{
            e.Row.Cells[
1].Visible = false;
        }

    }

}

CBook.cs:

using  System;
using  System.Data;
using  System.Data.OleDb;
using  System.Configuration;
using  System.Web;
using  System.Web.Security;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.WebControls.WebParts;
using  System.Web.UI.HtmlControls;

/// 
/// Summary description for CBook
/// 

public   class  CBook
{
    
/// 
    
/// DB连接字符串
    
/// 

    private static string connString = System.Configuration.ConfigurationManager.AppSettings["provider"].ToString() 
                              
+ System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dbPath"]) + ";";
    
public CBook()
    
{
        
//
        
// TODO: Add constructor logic here
        
//
    }


    
/// 
    
/// Execute sql NonQuery(insert,delete,update)
    
/// 

    
/// sql
    
/// OleDbParameter数组

    private static void ExeNonQuery(string sql, OleDbParameter[] parameters)
    
{
        OleDbConnection conn 
= new OleDbConnection(connString);
        
try
        
{
            conn.Open();

            OleDbCommand cmd 
= new OleDbCommand(sql, conn);

            cmd.Parameters.AddRange(parameters);
            cmd.ExecuteNonQuery();
        }

        
catch
        
{
            
throw;
        }

        
finally
        
{
            conn.Close();
        }

    }


    
/// 
    
/// 修改
    
/// 

    public static void Update(int id, string bookName, string author)
    
{
        
string sql = "update tableBook set BookName=@bookName,BookAuthor=@author where ID=@id";

        OleDbParameter[] parameters 
= new OleDbParameter[3];
        parameters[
0= new OleDbParameter("@bookName", bookName);
        parameters[
1= new OleDbParameter("@author", author);
        parameters[
2= new OleDbParameter("@id", id);

        ExeNonQuery(sql, parameters);
    }


    
/// 
    
/// 插入
    
/// 

    public static void Insert(string bookName, string author)
    
{
        
string sql = "insert into tableBook (bookName,BookAuthor)values(@bookName,@author)";

        OleDbParameter[] parameters 
= new OleDbParameter[2];
        parameters[
0= new OleDbParameter("@bookName", bookName);
        parameters[
1= new OleDbParameter("@author", author);

        ExeNonQuery(sql, parameters);
    }


    
/// 
    
/// 删除
    
/// 

    
/// 

    public static void Delete(int id)
    
{
        
string sql = "delete from tableBook where ID=@id";
        OleDbParameter paraID 
= new OleDbParameter("@id", id);

        ExeNonQuery(sql, 
new OleDbParameter[] { paraID });
    }

    
/// 
    
/// 返回DB中所有数据
    
/// 

    
/// 

    public static DataTable GetData()
    
{
        OleDbConnection conn 
= new OleDbConnection(connString);
        
try
        
{
            conn.Open();
            
string sql = "select * from tableBook";
            OleDbDataAdapter adapter 
= new OleDbDataAdapter(sql, conn);
            DataSet ds 
= new DataSet();
            adapter.Fill(ds, 
"bookTable");
            DataTable dt 
= ds.Tables[0];
            
return dt;
        }

        
catch
        
{
            
throw;
            
return null;
        }

        
finally
        
{
            conn.Close();
        }

    }


    
public static void ShowMessage(Page page, string msgInfo)
    
{
        page.Response.Write(
"");
    }

}

你可能感兴趣的:(WebForm)