C# – Gridview RowCommand event

cgridview

I have a gridview in which boundfield is somethig like this-

 <asp:BoundField  HeaderText="Approved" />

On this gridview's rowcommand event I want to show some text according to command name such as

protected void gwFacultyStaff_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Yes"))     
    {
        string id = e.CommandArgument.ToString();
        GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
        int index = Convert.ToInt32(row.RowIndex);
        GridViewRow rows = gwFacultyStaff.Rows[index];
        rows.Cells[12].Text = "TRUE";     
    }
    else if (e.CommandName.Equals("No"))
    {
        string id = e.CommandArgument.ToString();
        GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
        int index = Convert.ToInt32(row.RowIndex);
        GridViewRow rows = gwFacultyStaff.Rows[index];
        rows.Cells[12].Text = "FALSE";
    }
}

But its not showing me the required text which I want to display. Can anybody suggest me the possible solution?

Best Answer

Instead of a BoundField use a TemplateField, like this:

<asp:TemplateField HeaderText="Approved">
    <ItemTemplate>
        <asp:Label id="LabelApproved" runat="server"/>
    </ItemTemplate>
</asp:TemplateField>

Now in your RowCommand event, you can do this:

protected void gwFacultyStaff_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("Yes"))     
    {
        GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
        Label theLabel = row.FindControl("LabelApproved") as Label;
        theLabel.Text = "TRUE";
    }
    else if (e.CommandName.Equals("No"))
    {
        GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
        Label theLabel = row.FindControl("LabelApproved") as Label;
        theLabel.Text = "FALSE";
    }
}
Related Topic