Reputation: 1337
I have a gridview with an asp.net button that calls a C# method to update a database based on some data within the gridview row. That method gets the rowindex and the values to update the data record. I then want to hide the button for that row. I am using the code shown below:
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;
}
I get this error message {"Object reference not set to an instance of an object."} on the first line of code that hides the button.
If I use the same code for a method OnSelectedIndexChange and change the button to a LinkButton the code for hiding the link works but the code to update the database fails.
How can I get this code to work together?
Thanks
Upvotes: 0
Views: 989
Reputation: 2108
You just need to cast the sender
to a Control
and set it to 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;
}
Note: The sender
is the control that raise the event, also, I'm casting the sender
to a Control
because no matter if it is a Button
, LinkButton
, etc it will work for any Control
that has a Visible
property
Upvotes: 1