I have a gridview with a rowcommand
and a linkbutton
. When i press the linkbutton the row gets edited however the DDL should bound data with values from my databasetable but this does not work
I do not know if this is the correct way of doing this but i do get an error when pressing linkbutton "Object reference not set to an instance of an object." but i do not think that is the major problem here.
should i bound my DDL row when editing from a Rowcommand or can anyone see what im doing wrong?
ASPX markup for DDL column:
<asp:TemplateField HeaderText="Status">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatusRow" AppendDataBoundItems="True" runat="server" >
<asp:ListItem>Status</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfEditStatus" runat="server" ErrorMessage ="Status is a required field"
ControlToValidate="ddlStatusRow" Text="*" ForColor="Red" InitialValue="Status">
</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#E6E6E6" Font-Bold="False" Font-Names="Arial" Font-Size="14px" ForeColor="Black" />
<ItemStyle Font-Size="12px" HorizontalAlign="Center" Width="4%" />
</asp:TemplateField>
CodeBehind:
protected void gwUnplannedActivities_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
gwUnplannedActivities.EditIndex = rowIndex;
BindGridViewUnplannedActivities();
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
DropDownList ddlStatusRow = (DropDownList)row.Cells[3].FindControl("ddlStatusRow");
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM ....", con);
con.Open();
ddlStatusRow.DataSource = cmd.ExecuteReader();
ddlStatusRow.DataTextField = "Status";
ddlStatusRow.DataBind();
}
}
else if (e.CommandName == "CancelUpdate")
{
//somecode....
}
else if (e.CommandName == "UpdateRow")
{
//somecode....
}
}
Use this
GridView gv = (GridView)sender;
DropDownList ddlStatusRow = (DropDownList)gv.Rows[rowIndex].FindControl("ddlStatusRow");
Instead of
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
DropDownList ddlStatusRow = (DropDownList)row.Cells[3].FindControl("ddlStatusRow");
The problem is that the Edit Index has already been set, so row
does not exits anymore because it has been replaced with the Editable Row.