Click here to Skip to main content
15,922,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,


I need to know about how to work with Template field of gridviw...
I want to add a textbox in a gridview (say name), and fetch the value of name from database in that template field....
N next thing is how can i access n store that name value from template field in some other variable..

Help me for this,
Thanks in advance...
Posted

 
Share this answer
 
Hello,

C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var data = new List<Data>();
                data.Add(new Data { Id = 1, Name = "Abc" });
                data.Add(new Data { Id = 2, Name = "Abc2" });

                GridView1.DataSource = data;
                GridView1.DataBind();
            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var nameValue = (e.Row.FindControl("txtName") as TextBox).Text;
            }
        }

        protected void btnClick_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow item in GridView1.Rows)
            {
                Response.Write("<br />Your value - " + (item.FindControl("txtName") as TextBox).Text);
            }
        }



in .aspx file
XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                Name
            </HeaderTemplate>
            <ItemTemplate>
                <asp:TextBox ID="txtName" runat="server" Text='<%#Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button Text="Click" ID="btnClick" runat="server" OnClick="btnClick_Click" />
 
Share this answer
 
v2
Comments
Rohit Kolekar11 1-Apr-13 8:30am    
var data = new List();

Showing error for this.. Do i need to include any reference???
vijay__p 2-Apr-13 0:53am    
Just add one class with following definition

public class Data
{
public int Id { get; set; }

public string Name { get; set; }
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900