I am trying to use findcontrol TextBox in RowCommand of the gridview. But Error Object reference not set to an instance of an object.
Help me please.
Design
<asp:GridView ID="gvMaster" runat="server" AllowPaging="true" AutoGenerateColumns="False" OnRowCommand="gvMaster_RowCommand" Width="100%">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="ibtnEdit" runat="server" CommandName="edit" ImageUrl="~/images/edit.gif" ToolTip="Insert/Edit" />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td nowrap="nowrap">
<asp:ImageButton ID="ibtnSave" runat="server" CommandName="update" ImageUrl="~/images/icon-floppy.gif" ToolTip="Save" />
</td>
<td nowrap="nowrap">
<asp:ImageButton ID="ibtnCancel" runat="server" CommandName="cancel" ImageUrl="~/images/icon-cancel.gif" ToolTip="Cancel" />
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="30px" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Effective Date">
<ItemTemplate>
<asp:Label ID="lblEffectiveDate" runat="server" Text='<%# String.Format("{0:dd/MM/yyyy}", Eval("eff_date")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td nowrap="nowrap">
<asp:TextBox ID="txtEffDate2" runat="server" MaxLength="10" Text='<%# String.Format("{0:dd/MM/yyyy}", Eval("eff_date")) %>'
Width="70px" Style="text-align: center"></asp:TextBox>
</td>
</tr>
</table>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code BeHind:
protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToUpper().Equals("SELECT"))
{
}
else if (e.CommandName.ToUpper().Equals("EDIT"))
{
string cmdNmEdit = e.CommandName;
object cmdSrcEdit = e.CommandSource;
GridViewRow gvMaster = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
TextBox txtEffDate2 = gvMaster.FindControl("MyTextBoxId") as TextBox;
txtEffDate2.Text = DateTime.Now.ToString("DD/MM/yyyy"); //<------ Error This Line
}
}
How can use FindControl in the OnRowCommand of GridView?
Thanks in advance. ;)
The
CommandArgument
contains the row-index by default. That's why this works: