我想访问gridview中的下拉列表并将其选定的值保存到数据库中,但它不断给出错误,即对象引用未设置为对象的实例。
void Gridview1_RowUpdating用于使用图像按钮将值从gridview编辑保存到数据库。
下拉列表的html ID是gridview中的“DropDownList1”。还有其他选择吗?
C#:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
con2.Open();
using (con2)
{
DropDownList RoomID = e.RowIndex.FindControl("DropDownList1") as DropDownList;
string query = "UPDATE Info SET Forename=@Forename,LastName=@LastName,Email=@Email,Phone=@Phone,RoomID=@RoomName WHERE ID=@ID";
SqlCommand sqlCmd = new SqlCommand(query, con2);
sqlCmd.Parameters.AddWithValue("@Forename", (GridView1.Rows[e.RowIndex].FindControl("txtForeName") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@LastName", (GridView1.Rows[e.RowIndex].FindControl("txtLastName") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@Email", (GridView1.Rows[e.RowIndex].FindControl("txtEmail") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@Phone", (GridView1.Rows[e.RowIndex].FindControl("txtPhone") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@RoomName",Convert.ToInt32(RoomID.SelectedValue));
sqlCmd.Parameters.AddWithValue("@ID",Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated!";
lblErrorMessage.Text = "";
con2.Close();
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
答案 0 :(得分:0)
e.RowIndex
是int
,你不会在那里找到DropDownList。你需要
DropDownList RoomID = GridView1.Rows[e.RowIndex].FindControl("DropDownList1") as DropDownList;