无法从Gridview中获取值
本文关键字:获取 Gridview | 更新日期: 2023-09-27 18:03:25
我想通过我的gridview做一个更新操作,但我不能弄清楚。
我的gridview是这样的
<asp:GridView ID="GridView1" runat="server" ShowFooter="True" AutoGenerateColumns="False" DataKeyNames="ID"
OnDataBinding="GridView1_DataBinding"
OnRowDeleting="GridView1_RowDeleting"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserPW" HeaderText="UserPW" SortExpression="UserPW" />
<asp:BoundField DataField="UserType" HeaderText="UserType" SortExpression="UserType" />
</Columns>
</asp:GridView>
我的添加/删除工作得很好,但有一个问题与更新,如从网格获取空值。我尝试了3种不同的方法来获得值。注释行给了我NullReferenceException,而未注释的行没有,但是它们保存的值是空字符串。
这是我的aspx.cs更新。(我使用GridView的编辑/更新)
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userID = Convert.ToInt32(this.GridView1.DataKeys[e.RowIndex]["ID"]);
var UserOperations = new ModelOperations.UserList.UserListOperations();
//TextBox uname = (TextBox)this.GridView1.Rows[e.RowIndex].FindControl("UserName");
string uname = this.GridView1.Rows[e.RowIndex].Cells[2].Text;
string upw = this.GridView1.Rows[e.RowIndex].Cells[3].Text;
//string uname = this.GridView1.SelectedRow.Cells[2].Text;
//string upw = this.GridView1.SelectedRow.Cells[3].Text;
//TextBox upw = (TextBox)this.GridView1.Rows[e.RowIndex].FindControl("UserPW");
var result = UserOperations.updateUser(userID, uname, upw);
GridView1.EditIndex = -1;
GridView1.DataBind();
}
尝试:
string uname = e.NewValues["UserName"];
string upw = e.NewValues["UserPW"];
如果你愿意,你甚至可以将它与e.OldValues
进行比较。