I have created a custom template field for a gridview.When one clicks a button, the template field is supposed to be added to the gridview.
Here is the code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim assignment As String
assignment = txtAssignment.Text

Dim column As New TemplateField
column.ItemTemplate = New GridViewTemplate(DataControlRowType.DataRow, "txtbox")
column.HeaderStyle.Width = 4
column.HeaderText = assignment
column.HeaderStyle.CssClass = "verticaltext"
GridView1.Columns.Add(column)
GridView1.DataBind()

End Sub
Public Class GridViewTemplate
Implements ITemplate

Private templateType As DataControlRowType
Private columnName As String

Sub New(ByVal type As DataControlRowType, ByVal colname As String)

templateType = type
columnName = colname

End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case templateType
Case DataControlRowType.Header
' Create the controls to put in the header
' section and set their properties.
Dim lc As New Literal
lc.Text = "<b>" & columnName & "</b>"

' Add the controls to the Controls collection
' of the container.
container.Controls.Add(lc)
Case DataControlRowType.DataRow
Dim t As New TextBox
t.Width = 20
t.MaxLength = 3
container.Controls.Add(t)
End Select

End Sub
End Class

The problem is the rendering. When one clicks the button the template field is added with its textbox item templates.
However, when one clicks again, the textboxes of the previous temp field disappear completely. What is causing this?? All I want to do is to be able to add multiple temp fields with textboxes to the gridview and have the textboxes remain so that the user can put in a value.
This is so frustrating that no one can find a way to do this.

In a word - State

Remember asp.net is stateless. When you click the button click the page reloads first and so you lose the previously added column.

You need to turn on their viewstate

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.