Skip to content Skip to sidebar Skip to footer

How To Add An Empty, Unbound, Comment Column To A Gridview?

I've put together a GridView table in ASP.net that allows users to approve a series of records. As part of this approval process, I'd like to provide an empty column for the user t

Solution 1:

Just a simple solution I've quickly put together. It uses the OnRowCommand event of the GridView.

<asp:GridViewID="GridView1"runat="server"OnRowCommand="GridView1_RowCommand"><Columns><asp:TemplateFieldHeaderText="TextBox"><ItemTemplate><asp:TextBoxID="TextBox1"runat="server"TextMode="MultiLine"Text='<%# Eval("textfield") %>'></asp:TextBox></ItemTemplate></asp:TemplateField><asp:TemplateFieldHeaderText="UpdateButton"><ItemTemplate><asp:ButtonID="Button1"runat="server"Text="Update" /></ItemTemplate></asp:TemplateField></Columns></asp:GridView>

Code behind

protectedvoidGridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    //cast the sender back to a gridview
    GridView gv = sender as GridView;

    //cast the commandsource back to a button
    Button btn = e.CommandSource as Button;

    //cast the namingcontainer of the button back to a gridviewrow
    GridViewRow row = btn.NamingContainer as GridViewRow;

    //find the correct textbox using findcontrol and the index obtained from the row
    TextBox tb = gv.Rows[row.DataItemIndex].FindControl("TextBox1") as TextBox;

    //show result
    Label1.Text = tb.Text;
}

UPDATE

Or if you want to update all the records at once by pressing a button.

protectedvoidButton1_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView1.Rows)
    {
        TextBox tb = row.FindControl("TextBox1") as TextBox;
        Label1.Text += tb.Text + "<br>";
    }
}

Post a Comment for "How To Add An Empty, Unbound, Comment Column To A Gridview?"