Binding data to a textbox , inside a templatefield of a gridview » C# and ASP.NET

lglifesgood picture lglifesgood · Jun 23, 2010 · Viewed 9.8k times · Source

How can I bind data to a textbox which is in a templatefield of a gridview ? I want to use ExecuteScalar , get a value and throw it to that textbox .

Answer

Chris Mullins picture Chris Mullins · Jun 23, 2010

Basically you create a method to return your value and then call it in the databinding expression. Take a look at this example:

In your aspx page call the function GetValue in the data binding expression:

<asp:GridView ID="GridTest" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="txtValue" Width="200px" runat="server" Text='<%#GetValue((int)Container.DataItem)%>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Then in your code behind you have the function to get the value:

protected void Page_Load(object sender, EventArgs e)
{

    GridTest.DataSource = new List<int>{1, 2, 3};
    GridTest.DataBind();

}

protected string GetValue(int ID)
{
    return "Value from Execute Scalar " + ID;
}