The following is an excerpt from my row event handler for a GridView control. Ignore the insecure SQL; I'll parameterize it before it goes live.
if (e.CommandName == "cmdEdit")
{
Int32 index = Convert.ToInt32(e.CommandArgument);
gvStudents.EditIndex = index;
Int32 id = Convert.ToInt32(gvStudents.DataKeys[index].Value);
dsfname.SelectCommand = @"SELECT firstname FROM [a server] WHERE firstname IS NOT NULL AND idnum =" + id;
dslname.SelectCommand = @"SELECT lastname FROM [a server] WHERE lastname IS NOT NULL AND idnum =" + id;
dshours.SelectCommand = @"SELECT hours FROM [a server] WHERE hours IS NOT NULL AND idnum =" + id;
dsemail.SelectCommand = @"SELECT email FROM [a server] WHERE email IS NOT NULL AND idnum =" + id;
dsfname.DataBind();
dslname.DataBind();
dshours.DataBind();
dsemail.DataBind();
dsStudents.DataBind();
lblWarning.Text = ((GridViewRow)gvStudents.Rows[gvStudents.EditIndex]).RowState.ToString();
lblWarning.Visible = true;
lblWarning.Text += " " + index;
showGrid();
}
This runs when the user clicks on a button to begin an edit. As is, I'm displaying a label for testing purposes, lblWarning, and populating it with the row state of the selected row and its index. The row state is "normal", which seems to mean that the GridView's EditIndex hasn't been updated. I don't know why.
The commented out code at the bottom attempts to add an item to one of the DropDownLists. It's commented out because it causes an exception that says I'm referencing an object that doesn't exist. That is, it can't find the DropDownList.
I'm new to ASP, and don't really understand data binding, but it seems this issue is related to it. What do I need to do for that change of the EditIndex to take effect?
What I have tried:
Tried using validation. The code in the inner if block never fires.
if (gvStudents.Rows[gvStudents.EditIndex].RowType == DataControlRowType.DataRow)
{
if ((gvStudents.Rows[gvStudents.EditIndex].RowState & DataControlRowState.Edit) > 0)
{
((DropDownList)gvStudents.Rows[gvStudents.EditIndex].FindControl("ddlFirstName")).Items.Add("test item");
}
}