<Columns>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText= "<img border=0 src=ok.gif>" CancelText= "<imgborder=0 src=cancel.gif>" EditText= "<imgborder=0src=edit.gif>"></asp:EditCommandColumn>
<asp:ButtonColumn Text= "<img border= 0src= delete.gif>"CommandName="Delete"></asp:ButtonColumn>
<asp:BoundColumn DataField= "ProductID" SortExpression="ProductID" ReadOnly="True" HeaderText= "ProductID"></asp:BoundColumn>
<asp:BoundColumn DataField= "ProductName" SortExpression="ProductName" HeaderText= "ProductName"></asp:BoundColumn>
<asp:BoundColumn DataField="QuantityPerUnit" SortExpression="QuantityPerUnit" HeaderText= "Quantity PerUnit"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitPrice" SortExpression="UnitPrice" HeaderText= "Unit Price"DataFormatString="{0:c}"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitsInStock" SortExpression="UnitsInStock" HeaderText= "Units InStock"></asp:BoundColumn>
<asp:BoundColumn DataField="UnitsOnOrder" SortExpression="UnitsOnOrder" HeaderText= "Units OnOrder"></asp:BoundColumn>
<asp:BoundColumn DataField= "ReorderLevel" SortExpression="ReorderLevel" HeaderText= "ReorderLevel"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Discontinued" SortExpression="Discontinued">
<ItemTemplate>
<asp:CheckBox id= "Discontinued" runat="server" Checked= '<%# DataBinder.Eval(Container.DataItem, "Discontinued")%>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
你看,是不是不难?关键在于我们常动手动脑。多看资料也很关键哦!
C#后台程序:
让我们先看一段程序:
private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
上面展现的是一种非常好的技术,当页面不是PostBack状态时,就绑定数据。这意味着,一旦页面被请求数据将被绑定。
继续看程序:
/// <summary>
/// 这个函数返回关于产品细节的DataSet
/// </summary>
///<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。下一步,让我们看如何编辑记录:
/// <summary>
/// 这个函数只有当用户点击Edit按钮时才会被激活
/// </summary>
/// <paramname="sender"></param>
/// <paramname="E"></param>
protected void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs E)
{
///找出被选定项目的索引(ItemIndex),并且进一步绑定数据
MyDataGrid.EditItemIndex = (int)E.Item.ItemIndex;
BindGrid();
}
通过上面代码所附带的注解大家也能明白MyDataGrid_Edit函数的功能:当用户点击Edit按钮时激活MyDataGrid_Edit函数,并且程序找到所要编辑的记录的索引,把该索引号分配给DataGrid的EditItemIndex属性。
如果用户点击Cancel按钮,将调用我们在上面的.aspx文件中提到的MyDataGrid_Cancel函数,程序如果分配给DataGrid属性 EditItemIndex的值为-1,就意味着用户没有选择Edit,程序如下:
/// <summary>
/// 用户点击Cancel按钮时激活MyDataGrid函数
/// </summary>
/// <paramname="sender"></param>
/// <paramname="E"></param>
protected void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs E)
{
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
下面的代码像我们展现了如何从DataGrid中删除一条选中的记录。我们知道Web控件DataGrid有一DataKeyField属性,事实上它就包含了每条记录的ProductID字段值。您一定会问如何通过DataKeyField属性得到DataGrid中选中记录的ProductID值呢?下面这段代码会让您释然的:
-----
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
-----
MyDataGrid_Delete函数代码如下:
/// <summary>
///从DataSet中删除一条记录
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Delete(Object sender, DataGridCommandEventArgs E)
{
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
string SQLStatement="Delete Products WHERE ProductID="+ProductID;
string myConnectionString = "server=localhost;uid=sa;pwd=;database=NorthWind";
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand (SQLStatement,myConnection);
myCommand.CommandTimeout = 15;
myCommand.CommandType=CommandType.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception ee)
{
throw ee;
}
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
下面的代码用来更新NorthWind数据库的产品信息,
我们可以使用下面这项技术检索值:
-------------------
bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
-------------------
这时我们使用FinControl()方法就能得到Discontinued CheckBox的值.
/// <summary>
///更新记录
/// </summary>
/// <param name="sender"></param>
/// <param name="E"></param>
protected void MyDataGrid_Update(Object sender, DataGridCommandEventArgs E)
{
int ProductID =(int)MyDataGrid.DataKeys[(int)E.Item.ItemIndex];
string ProductName = ((TextBox)E.Item.Cells[3].Controls[0]).Text;
string QuantityPerUnit=((TextBox)E.Item.Cells[4].Controls[0]).Text;
string UnitPrice = ((TextBox)E.Item.Cells[5].Controls[0]).Text;
Int16 UnitsInStock=Int16.Parse(((TextBox)E.Item.Cells[6].Controls[0]).Text);
Int16 UnitsOnOrder=Int16.Parse(((TextBox)E.Item.Cells[7].Controls[0]).Text);
Int16 ReorderLevel=Int16.Parse(((TextBox)E.Item.Cells[8].Controls[0]).Text);
bool Discon=((CheckBox)E.Item.FindControl("Discontinued")).Checked;
int result;
if(!Discon)
{
result=0;
}
else
{
result=1;
}
string SQLStatement="UPDATE Products "+
"SET ProductName='"+ProductName+"', "+
"QuantityPerUnit='"+QuantityPerUnit+"', "+
"UnitPrice ="+UnitPrice.Substring(UnitPrice.IndexOf("¥")+1)+", "+
"UnitsInStock ="+UnitsInStock+", "+
"UnitsOnOrder ="+UnitsOnOrder+", "+
"ReorderLevel ="+ReorderLevel+", "+
"Discontinued ="+result+
" WHERE ProductID ="+ProductID;
string myConnectionString = "server=localhost;uid=xjb;pwd=xjb;database=Northwind";
SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand(SQLStatement,myConnection);
myCommand.CommandTimeout = 15;
myCommand.CommandType = CommandType.Text;
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception ee)
{
throw ee ;
}
MyDataGrid.EditItemIndex = -1;
BindGrid();
}
接下来的BindGrid()调用私有函数GetProductData取得DataSet对象并绑定到DataGrid控件。
/// <summary>
/// 接受数据库数据并再次绑定
/// </summary>
protected void BindGrid()
{
MyDataGrid.DataSource=GetProductData().Tables["Products"].DefaultView;
MyDataGrid.DataBind();
}
用户在DataGrid中向前或向后移动时激活MyDataGrid_PageIndexChanged事件,因为DataGrid 不能自动的获取新页的索引号,所以我们只能手动取得索引号。
/// <summary>
/// 分页操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MyDataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
MyDataGrid.CurrentPageIndex=e.NewPageIndex;
BindGrid();
}
用户在任何时候想对数据分类时,就激活下面的Sort_Grid事件。例如,如果用户点击field headers,事件就将被激活,并且把数据分成我们想要的分类。 我们需要DataView对象去为e.SortExpression.ToString()方法分类,返回的是被点击域标题的分类。
/// <summary>
/// 分类
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
{
DataView dv= new DataView(GetProductData().Tables["Products"]);
dv.Sort= e.SortExpression.ToString();
MyDataGrid.DataSource=dv;
MyDataGrid.DataBind();
}
执行结果:
该程序在win2000+SqlServer2000+VS.NETBeta2环境下测试成功,程序执行结果