sd_dracula
sd_dracula

Reputation: 3896

asp:gridview dynamically created columns

I have a gridview which gets populated with the help of a sqldatasource.

Once the gridview is created I want to add a manual column created Notes so that the user can enter notes for each row and then click the submit the form.

In the <Columns> field of the grid view I have this:

<asp:TemplateField HeaderText="Notes">
                    <ItemTemplate>
                        <asp:TextBox ID="txtNotes" runat="server"></asp:TextBox>
                    </ItemTemplate>
</asp:TemplateField>

This actually creates the new column just fine but when I enter data in the textboxes it disappears when clicking submit. In the submit even I iterate through each gridview row like so:

foreach (GridViewRow row in gvResults.Rows)
{ 
   row.Cells[0].Text = 
   ...
   string notes = (row.Cells[10].FindControl("txtNotes") as TextBox).Text;
}

So the string notes is always empty, it seems that on postback the value is reset; because it recreates the txtNotes textbox.

How can I keep the value on postback?

Upvotes: 0

Views: 1194

Answers (1)

mason
mason

Reputation: 32694

When you bind the GridView, make sure you check to see if it's a postback.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        LoadData(); //if you did this without checking IsPostBack, you'd rebind the GridView and lose the existing rows
    }

protected void LoadData()
{
    //bind GridView etc
}

Upvotes: 3

Related Questions