Reputation: 342
I have a grid view which contains 4 template fields, each containing a text box.
Now I have bound these template fields with a datasource. When I as a user type in some data in the text box and click on save button (a button which is not a part of gridview but an individual one in the webform), I am not able to get the values in the click event handler in the code behind file. Please help me.
ASPX file
<asp:TemplateField HeaderText="col1">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt1" runat="server" Text='<%# Bind("[col1]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col2">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server" Text='<%# Bind("[col2]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col3">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt3" runat="server" Text='<%# Bind("[col3]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="col4">
<ControlStyle Height="25px" Width="60px" />
<ItemTemplate>
<asp:TextBox ID="txt4" runat="server" Text='<%# Bind("[col4]") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
Code behind file
protected void ButtonAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvEdit.Rows)
{
string a = ((TextBox)row.FindControl("col1")).Text;
//above line gives a null value
}
}
Upvotes: 0
Views: 852
Reputation: 23958
You need to loop through the GridViewRowCollection
, and then for each row, find the control by the Id
you gave it in the markup. For example:
protected void ButtonAdd_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvEdit.Rows)
{
var txt1 = row.FindControl("txt1") as TextBox;
var txt2 = row.FindControl("txt2") as TextBox;
var txt3 = row.FindControl("txt3") as TextBox;
var txt4 = row.FindControl("txt4") as TextBox;
// access the Text property of each, e.g. txt1.Text
}
}
Update: Make sure that when you do the data source binding, it only happens on the initial load and not subsequent postbacks, otherwise your changes will be reset each time.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = // data source
GridView1.DataBind();
}
}
Upvotes: 1