abbas
abbas

Reputation: 23

asp.net grid view bound field to text box

I have a boundfield in a gridview. How can I change the boundfield to a textbox only for a specific column?

I tried

BoundField colname= new BoundField();
grid.Columns.Add(colname as TextBox);

But it goves a cast expression

Upvotes: 2

Views: 8860

Answers (1)

James Johnson
James Johnson

Reputation: 46047

I'm not sure if this will work for your situation, but you could try using a template field, like this:

<asp:TemplateField>
    <ItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("SomeValue")%>' ... />
    </ItemTemplate>
</asp:TemplateField>

EDIT: Adding TextBox to item template from code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) 
    {
        TemplateField txtColumn = new TemplateField();
        txtColumn.ItemTemplate = new TextColumn();
        GridView1.Columns.Add(txtColumn);
    }
}

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

EDIT: Setting text of dynamically added TextBox

//get the cell and clear any existing controls
TableCell cell = e.Row.Cells[0];
cell.Controls.Clear();

//create a textbox and add it to the cell
TextBox txt = new TextBox(); 
txt.Text = cell.Text;    
cell.Controls.Add(txt);

Upvotes: 2

Related Questions