我有一个带有asp.net按钮的gridview,它调用C#方法根据gridview行中的某些数据更新数据库。该方法获取rowindex和值以更新数据记录。然后我想隐藏该行的按钮。我使用下面显示的代码:
protected void AddJacket_Click(object sender, EventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;
//Get the value of column from the DataKeys using the RowIndex.
int id1 = Convert.ToInt32(GridViewSubjectList.DataKeys[rowIndex].Values[0]);
int id2 = Convert.ToInt32(GridViewSubjectList.DataKeys[rowIndex].Values[1]);
using (CADWEntities db = new CADWEntities())
{
var results = db.Subjects.SingleOrDefault(uu => uu.SubjectId == id1);
results.JacketNumber = Convert.ToString(id2);
db.SaveChanges();
}
//Hide the button after being click
Button Button = GridViewSubjectList.SelectedRow.Cells[0].FindControl("btnAddJacket") as Button;
Button.Enabled = false;
Button.Visible = false;
}
我在隐藏按钮的第一行代码中收到此错误消息{“对象引用未设置为对象的实例。”}。
如果我对方法OnSelectedIndexChange使用相同的代码并将按钮更改为LinkButton,则隐藏链接的代码可以正常工作,但更新数据库的代码将失败。
如何让这段代码一起工作?
由于
答案 0 :(得分:1)
您只需将sender
投射到Control
并将其设为visible = false
protected void AddJacket_Click(object sender, EventArgs e)
{
//Determine the RowIndex of the Row whose Button was clicked.
int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;
//Get the value of column from the DataKeys using the RowIndex.
int id1 = Convert.ToInt32(GridViewSubjectList.DataKeys[rowIndex].Values[0]);
int id2 = Convert.ToInt32(GridViewSubjectList.DataKeys[rowIndex].Values[1]);
using (CADWEntities db = new CADWEntities())
{
var results = db.Subjects.SingleOrDefault(uu => uu.SubjectId == id1);
results.JacketNumber = Convert.ToString(id2);
db.SaveChanges();
}
//Hide the button after being click
(sender as Control).Visible = false;
}
注意:sender
是引发事件的控件,同样,我将sender
转换为Control
,因为无论它是{{1} }},Button
等适用于具有LinkButton
属性的任何Control