user2209880
user2209880

Reputation:

add text box in grid view

I want change the content in grid view to textbox.
Here is part of my code

public class TextBoxTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
        TextBox txtBox = new TextBox();
        txtBox.ID = "txtBox";

        container.Controls.Add(txtBox);
    }
}

//dtTeaching is data sourse for grid view

foreach (DataColumn col in dtTeaching.Columns)
{       
   if (col.ColumnName.Contains("Name"))
   {
       TemplateField tfName = new TemplateField();
       tfName.ItemTemplate = new TextBoxTemplate();
       tfName.HeaderText = "Programme Name";
       gvTeaching.Columns.Add(tfName);
   }
 }

 gvTeaching.DataSource = dtTeaching;
 gvTeaching.DataBind();


 for (int i = 0; i < gvTeaching.Rows.Count; i++)
 {
     TextBox k = (TextBox)gvTeaching.Rows[i].Cells[0].Controls[0];
     k.Text = "test";
 }

But the result is nothing will display in the grid view.
No textbox no content, just 3 blank rows,

Upvotes: 0

Views: 24715

Answers (2)

Rahul Gokani
Rahul Gokani

Reputation: 1708

Can you take:

TemplateField tfName = new TemplateField();
tfName.EditTemplate = new TextBoxTemplate();
tfName.HeaderText = "Programme Name";
gvTeaching.Columns.Add(tfName);

You can try to add EditTemplate for editing the value in GridView.

Or You can simply add those fields on GridView.
Like:
......

<Columns>
   <asp:TemplateField>
      <ItemTemplate>
         <asp:Label ID="lbl" runat="server" Text='<%#Bind("ColumnName") %>' />
      </ItemTemplate>
      <EditTemplate>
         <asp:TextBox ID="txt" runat="server" Text='<%#Bind("ColumnName")%>' />
      </EditTemplate>
   </asp:TemplateField>
</Columns>

When the grid will be displayed on the page data will be placed in Label and when you edit that row it will be displayed in TextBox.

Upvotes: 1

शेखर
शेखर

Reputation: 17604

Why don't you use Template field.
At design time why at run-time?

Here is a example of template field

<asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
  <EditItemTemplate>
    <asp:TextBox ID="TextBox1" runat="server"
        Text='<%# Bind("FirstName") %>'></asp:TextBox>
  </EditItemTemplate>
  <ItemTemplate>
    <asp:Label ID="Label1" runat="server"
        Text='<%# Bind("FirstName") %>'></asp:Label>
    <asp:Label ID="Label2" runat="server"
        Text='<%# Bind("LastName") %>'></asp:Label>
  </ItemTemplate>
 </asp:TemplateField>

Upvotes: 2

Related Questions