gridview的编辑,更新,取消,自动分页等-飞外

gridview编辑列,把左下角的"自动生成字段"的复选框的勾去掉

添加boundfield(绑定列)将其datafield设置为productname,headertext设置为"产品名"

再添加commadfield下的编辑,更新,取消

确定

.cs文件按中编写一绑定gridview数据的方法:

public void bind()
{
SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=Northwind");
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from products", conn);
DataSet ds = new DataSet();
sda.Fill(ds);
conn.Close();
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
}

在load事件中调用bind()方法.......

将gridview的datakeynames设置为productid(和datalist的datakeyfield有点像)

1.编辑:

找到gridview的RowEditing事件:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex; //编辑的行设置为鼠标作用的当前行
bind(); //一定要进行绑定
}

2.更新:找到gridview的RowUpdating事件:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

{
int i = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value); //关键代码:取当前选中行产品的id
string productname = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text; //关键代码:取编辑框中产品名(改过后的名称),Rows[e.RowIndex].Cells[0].Controls[0]表示当前行,:

将gridview的allowpaging设置为true,pagesize自己定义如5

找到gridview的PageIndexChanging事件:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind(); //一定要重新绑定,否则是没效果的
}

5.gridview的rowcommand事件中取主键://模板列中放一button并把他的commandname设置为show

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "show")
{
//GridViewRow drv=((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent));
//string index = drv.RowIndex.ToString(); //行号
//string admin_id = GridView1.DataKeys[Convert.ToInt32(index)].Value.ToString(); //主键
//Response.Write(index+";"+admin_id);

//下面的方法需要在前台把button的 CommandArgument =' %# Eval("admin_id")% '

int admin_id=Convert.ToInt32(e.CommandArgument.ToString()); //主键
int index = Convert.ToInt32(((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent)).RowIndex); //行号
Response.Write(admin_id+";"+index);


}
}