前言:
这篇文章主要介绍如何在DataGrid控件中实现编辑、删除、分类以及分页操作。为了实现我们的意图,我们使用SqlServer2000自带的NorthWind数据库。程序分为两部分:
1.包含HTML代码的.ASPX文件
2.包含所有逻辑及方法的后台C#类文件
代码:
ASPX文件:
在这里我们设计了一个DataGrid对象,我为一些属性和方法作了注解。它就变得如此的简单:
1<asp:datagrid allowpaging="True" allowpaging属性的"true"时,="" allowsorting="True" autogeneratecolumns="False" backcolor="White" bordercolor="White" borderstyle="Ridge" borderwidth="2px" cellpadding="3" cellspacing="1" datagrid的每条记录都包含一个productid字段="" datakeyfield="ProductID" gridlines="None" horizontalalign="Left" id="MyDataGrid" mydatagrid_edit"="" numberin="" oncancelcommand="MyDataGrid_Cancel //这一事件激活MyDataGrid_Cancel函数(function)取消当前操作
2OnEditCommand=" ondeletecommand="MyDataGrid_Delete" onpageindexchanged="MyDataGrid_PageIndexChanged" onsortcommand="Sort_Grid" onupdatecommand="MyDataGrid_Update" pagerstyle-horizontalalign="Center" pagerstyle-mode="NextPrev" pagerstyle-nextpagetext="Next" pagerstyle-position="TopAndBottom" pagerstyle-prevpagetext="Previous" pagesize="15" previous和page="" runat="server" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 104px" 可进行分页操作="" 当用户对datagrid分类时激活sort_grid(function)函数="" 当用户进行翻页操作时就激活mydatagrid_pageindexchanged函数(function)="" 有2种模式风格:next="" 设每页25条记录="" 设置自动产生行为"false"="" 这一事件激活mydatagrid_delete函数(function)删除一条记录="" 这一事件激活mydatagrid_edit函数(function)编辑一条记录="" 这一事件激活mydatagrid_update函数(function)更新一条记录="" 这是分类属性="">
3<footerstyle backcolor="#C6C3C6" forecolor="Black"></footerstyle>
4<headerstyle backcolor="#4A3C8C" font-bold="True" forecolor="#E7E7FF"></headerstyle>
5<pagerstyle backcolor="#C6C3C6" forecolor="Black" horizontalalign="Right" nextpagetext="Next" position="TopAndBottom" prevpagetext="Previous"></pagerstyle>
6<selecteditemstyle backcolor="#9471DE" font-bold="True" forecolor="White"></selecteditemstyle>
7<itemstyle backcolor="#DEDFDE" forecolor="Black"></itemstyle>
8<columns>
9<asp:editcommandcolumn buttontype="LinkButton" canceltext="<imgborder=0 src=cancel.gif>" edittext="<imgborder=0src=edit.gif>" updatetext="<img border=0 src=ok.gif>"></asp:editcommandcolumn>
10<asp:buttoncolumn commandname="Delete" text="<img border= 0src= delete.gif>"></asp:buttoncolumn>
11<asp:boundcolumn datafield="ProductID" headertext="ProductID" readonly="True" sortexpression="ProductID"></asp:boundcolumn>
12<asp:boundcolumn datafield="ProductName" headertext="ProductName" sortexpression="ProductName"></asp:boundcolumn>
13<asp:boundcolumn datafield="QuantityPerUnit" headertext="Quantity PerUnit" sortexpression="QuantityPerUnit"></asp:boundcolumn>
14<asp:boundcolumn datafield="UnitPrice" dataformatstring="{0:c}" headertext="Unit Price" sortexpression="UnitPrice"></asp:boundcolumn>
15<asp:boundcolumn datafield="UnitsInStock" headertext="Units InStock" sortexpression="UnitsInStock"></asp:boundcolumn>
16<asp:boundcolumn datafield="UnitsOnOrder" headertext="Units OnOrder" sortexpression="UnitsOnOrder"></asp:boundcolumn>
17<asp:boundcolumn datafield="ReorderLevel" headertext="ReorderLevel" sortexpression="ReorderLevel"></asp:boundcolumn>
18<asp:templatecolumn headertext="Discontinued" sortexpression="Discontinued">
19<itemtemplate>
20<asp:checkbox checked='```
21# DataBinder.Eval(Container.DataItem, "Discontinued")
22```' id="Discontinued" runat="server"></asp:checkbox>
23</itemtemplate>
24</asp:templatecolumn>
25</columns>
26</asp:datagrid>
你看,是不是不难?关键在于我们常动手动脑。多看资料也很关键哦!
C#后台程序:
让我们先看一段程序:
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
上面展现的是一种非常好的技术,当页面不是PostBack状态时,就绑定数据。这意味着,一旦页面被请求数据将被绑定。
继续看程序:
///
1<summary>
2/// 这个函数返回关于产品细节的DataSet
3/// </summary>
///
1<returns></returns>
private DataSet GetProductData()
{
///SQLStatement是一个SQL语句(string型的)
string SQLStatement="SELECT Products.ProductID, Products.ProductName, Products.QuantityPerUnit, Products.UnitPrice, "+
"Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued "+
"FROM Products"; :
///声明 SqlConnection对象:myConnection
SqlConnection myConnection=new SqlConnection(@"server=(local)\NetSDK;”+
”database=NorthWind;uid=northwind;pwd=northwind;");
///声明Command对象:myCommand
SqlDataAdapter myCommand = new SqlDataAdapter(SQLStatement,myConnection);
///设置Command命令的类型为Text类型
myCommand.SelectCommand.CommandType=CommandType.Text;
///创建DataSet对象实例
myDataSet = new DataSet();
///把从表Products返回的数据填充myData
myCommand.Fill(myDataSet, "Products");
///最后返回myDataSet对象
return myDataSet;
}
这段代码执行给定的SQL语句访问数据库,私有函数GetProductData返回一个包含数据记录的DataSet。下一步,让我们看如何编辑记录:
///
1<summary>
2/// 这个函数只有当用户点击Edit按钮时才会被激活
3/// </summary>
///
1<paramname="sender">
2/// <paramname="e">
3protected void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
4{
5///找出被选定项目的索引(ItemIndex),并且进一步绑定数据
6MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
7BindGrid();
8}
9通过上面代码所附带的注解大家也能明白MyDataGrid_Edit函数的功能:当用户点击Edit按钮时激活MyDataGrid_Edit函数,并且程序找到所要编辑的记录的索引,把该索引号分配给DataGrid的EditItemIndex属性。
10如果用户点击Cancel按钮,将调用我们在上面的.aspx文件中提到的MyDataGrid_Cancel函数,程序如果分配给DataGrid属性 EditItemIndex的值为-1,就意味着用户没有选择Edit,程序如下:
11/// <summary>
12/// 用户点击Cancel按钮时激活MyDataGrid函数
13/// </summary>
14/// <paramname="sender">
15/// <paramname="e">
16protected void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
17{
18MyDataGrid.EditItemIndex = -1;
19BindGrid();
20}
21下面的代码像我们展现了如何从DataGrid中删除一条选中的记录。我们知道Web控件DataGrid有一DataKeyField属性,事实上它就包含了每条记录的ProductID字段值。您一定会问如何通过DataKeyField属性得到DataGrid中选中记录的ProductID值呢?下面这段代码会让您释然的:
22\-----
23int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
24\-----
25MyDataGrid_Delete函数代码如下:
26/// <summary>
27///从DataSet中删除一条记录
28/// </summary>
29/// <param name="sender"/>
30/// <param name="E"/>
31protected void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs E)
32{
33int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
34string SQLStatement="Delete Products WHERE ProductID="+ProductID;
35string myConnectionString = "server=localhost;uid=sa;pwd=;database=NorthWind";
36
37SqlConnection myConnection = new SqlConnection(myConnectionString);
38SqlCommand myCommand = new SqlCommand (SQLStatement,myConnection);
39
40myCommand.CommandTimeout = 15;
41myCommand.CommandType=CommandType.Text;
42
43try
44{
45myConnection.Open();
46myCommand.ExecuteNonQuery();
47myConnection.Close();
48}
49catch(Exception ee)
50{
51throw ee;
52}
53MyDataGrid.EditItemIndex = -1;
54BindGrid();
55}
56下面的代码用来更新NorthWind数据库的产品信息,
57我们可以使用下面这项技术检索值:
58\-------------------
59bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
60\-------------------
61这时我们使用FinControl()方法就能得到Discontinued CheckBox的值.
62/// <summary>
63///更新记录
64/// </summary>
65/// <param name="sender"/>
66/// <param name="E"/>
67protected void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
68{
69int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
70string ProductName = ((TextBox)E.Item.Cells[3].Controls[0]).Text;
71string QuantityPerUnit=((TextBox)E.Item.Cells[4].Controls[0]).Text;
72string UnitPrice = ((TextBox)E.Item.Cells[5].Controls[0]).Text;
73Int16 UnitsInStock=Int16.Parse(((TextBox)E.Item.Cells[6].Controls[0]).Text);
74Int16 UnitsOnOrder=Int16.Parse(((TextBox)E.Item.Cells[7].Controls[0]).Text);
75Int16 ReorderLevel=Int16.Parse(((TextBox)E.Item.Cells[8].Controls[0]).Text);
76bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
77int result;
78
79if(!Discon)
80{
81result=0;
82}
83else
84{
85result=1;
86}
87string SQLStatement="UPDATE Products "+
88"SET ProductName='"+ProductName+"', "+
89"QuantityPerUnit='"+QuantityPerUnit+"', "+
90"UnitPrice ="+UnitPrice.Substring(UnitPrice.IndexOf("¥")+1)+", "+
91"UnitsInStock ="+UnitsInStock+", "+
92"UnitsOnOrder ="+UnitsOnOrder+", "+
93"ReorderLevel ="+ReorderLevel+", "+
94"Discontinued ="+result+
95" WHERE ProductID ="+ProductID;
96
97string myConnectionString = "server=localhost;uid=xjb;pwd=xjb;database=Northwind";
98SqlConnection myConnection = new SqlConnection(myConnectionString);
99SqlCommand myCommand = new SqlCommand(SQLStatement,myConnection);
100
101myCommand.CommandTimeout = 15;
102myCommand.CommandType = CommandType.Text;
103
104try
105{
106myConnection.Open();
107myCommand.ExecuteNonQuery();
108myConnection.Close();
109}
110catch(Exception ee)
111{
112throw ee
113}
114
115MyDataGrid.EditItemIndex = -1;
116BindGrid();
117}
118
119接下来的BindGrid()调用私有函数GetProductData取得DataSet对象并绑定到DataGrid控件。
120/// <summary>
121/// 接受数据库数据并再次绑定
122/// </summary>
123protected void BindGrid()
124{
125MyDataGrid.DataSource=GetProductData().Tables["Products"].DefaultView;
126MyDataGrid.DataBind();
127}
128用户在DataGrid中向前或向后移动时激活MyDataGrid_PageIndexChanged事件,因为DataGrid 不能自动的获取新页的索引号,所以我们只能手动取得索引号。
129/// <summary>
130/// 分页操作
131/// </summary>
132/// <param name="sender"/>
133/// <param name="e"/>
134protected void MyDataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
135{
136MyDataGrid.CurrentPageIndex=e.NewPageIndex;
137BindGrid();
138}
139用户在任何时候想对数据分类时,就激活下面的Sort_Grid事件。例如,如果用户点击field headers,事件就将被激活,并且把数据分成我们想要的分类。 我们需要DataView对象去为e.SortExpression.ToString()方法分类,返回的是被点击域标题的分类。
140/// <summary>
141/// 分类
142/// </summary>
143/// <param name="sender"/>
144/// <param name="e"/>
145protected void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
146{
147
148DataView dv= new DataView(GetProductData().Tables["Products"]);
149dv.Sort= e.SortExpression.ToString();
150MyDataGrid.DataSource=dv;
151MyDataGrid.DataBind();
152}</paramname="e"></paramname="sender"></paramname="e"></paramname="sender">