Lucas_Santos
Lucas_Santos

Reputation: 4740

TextBox inside a GridView

I want to get the Text property from a TextBox that is inside a GridView. This TextBox has some data that come from my database. When I change this data, I wanna do a Update in my database.

But when I search for the Text of my TextBox, he get the old value that come from my database and not the value that I put now.

How can I do, to get my actual data that I write in my TextBox and not that come from my databse ?

protected void VerifyPriority()
{
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        GridViewRow RowView = (GridViewRow)GridView1.Rows[i];
        TextBox txt = (TextBox)GridView1.Rows[i].FindControl("txtPriority");

        if (txt != null)
        {
            if (txt.Text != this.changes[i])
            {
                this.UpdatePriority(this.codigo[i], txt.Text);
            }
        }
    }
}

Upvotes: 4

Views: 5215

Answers (1)

James Johnson
James Johnson

Reputation: 46067

More than likely you're you're rebinding the GridView after every postback instead of binding it once and letting ViewState persist the data. If you bind the GridView every time the page is posted back, any changes you make will be wiped out and replaced with the information from the database.

Do your binding on the first page load only (in this case):

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        GridView1.DataSource = GetSomeData();
        GridView1.DataBind();
    }
}

After putting the above code in place, you should be able to get the correct data from the TextBox:

foreach (GridViewRow row in GridView1.Rows)
{
    TextBox txt = row.FindControl("TextBox1") as TextBox;
    if (txt != null)
    {
        string value = txt.Text;
    }
}

Upvotes: 5

Related Questions