-2

I have an asp.net 4.5 web application and I'm trying to add a textbox in a gridview from C#. How can I do that? All the examples I found are about setting an ItemTemplate and adding a TextBox in it. That's not what I want.

So I have this:

<asp:GridView ID="InsertReportData" runat="server" Visible="False">
<Columns>
</Columns>
</asp:GridView>

I have managed to add boundfield and itemtemplate with this:

BoundField bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
InsertReportData.Columns.Add(bfield);

TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
InsertReportData.Columns.Add(tfield);

How can I add a textbox in this tfield? I should be able to it with:

tfield.ItemTemplate.InstantiateIn();//but when I tried adding a textbox here, it didn't work..can't compile..error.

Can this be done somehow?

1

1 Answer 1

1

Refer here for more asp.net grid view bound field to text box

create a new class by inheriting ITemplate like below

public class TextColumn : ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        TextBox txt = new TextBox();
        txt.ID = "MyTextBox";
        container.Controls.Add(txt);
    }
}

and use like below code when you want to add new text box

TemplateField txtColumn = new TemplateField();
txtColumn.ItemTemplate = new TextColumn();
GridView1.Columns.Add(txtColumn);
Sign up to request clarification or add additional context in comments.

4 Comments

??????? did you even read my post ?? Where did I say I want to add a textbox in a bound field ? I want to add a textbox to a gridview from C#. Not to have it in an ItemTemplate from the beginning.
have you checked this answer? stackoverflow.com/questions/7324718/…
Have you read my post ? I don't want to add an ItemTemplate. I want to generate everything from C#.
YES ! I already implemented that class that inherited from ITemplate but my mystake was when I was doing txtColumn.ItemTemplate = new TextColumn(); //I was using new TextBox(). Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.