.net2.0 GridView删除、修改问题
<asp:GridView ID= "GridView1 " runat= "server " AutoGenerateColumns= "False " Height= "115px " Width= "800px ">
<Columns>
<asp:BoundField DataField= "wc_id " Visible= "False " />
<asp:ButtonField ButtonType= "Button " CommandName= "update " Text= "修改 " />
<asp:ButtonField CommandName= "delete " Text= "删除 " />
</Columns>
</asp:GridView>
我在GridView 上绑定2个按钮列,我想点删除或修改的时候能够获取对应行数据的键值,可是我在GridView1_RowUpdating和GridView1_RowDeleting这两个事件中写string id = GridView1.SelectedValue.ToString ();这句代码的时候,报错:
未将对象引用设置到对象的实例。 请问问题出在哪里?
------解决方案--------------------删除时要用到表的主键,所以要先把主键存起来.
用this.GridView1.DataKeyNames=new String[] {EmployeeID};放到数据显示方法里。
然后在GridView1_RowDeleting中先将要删除的主键取出来,string empID = this.GridView1.DataKeys[e.RowIndex].Values[0].ToString();
最后正常的删除语句,条件是当id=empID时。
------解决方案--------------------protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ButtonField btn = (ButtonField)e.Row.Cells[*].Controls[0];
btn.CommandArgument = e.Row.RowIndex.ToString();//给ButtonField绑定行索引
}
}