' Visual Basic Private Property DynamicColumnAdded() As Boolean Get If ViewState("ColumnAdded") Is Nothing Then Return False Else Return True End If End Get Set(ByVal Value As Boolean) ViewState("ColumnAdded") = Value End Set End Property
Protected Overrides Sub LoadViewState(ByVal savedState As Object) MyBase.LoadViewState(savedState) If Me.DynamicColumnAdded Then Me.AddColums() End If End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Check property to be sure columns are not added more than once If Me.DynamicColumnAdded Then Return Else Me.AddColums() End If End Sub
Protected Sub AddColums() ' Add two columns Dim dgc_id As New BoundColumn() dgc_id.DataField = "instock" dgc_id.HeaderText = "In Stock?" dgc_id.ItemStyle.Width = New Unit(80) DataGrid1.Columns.Add(dgc_id)
Dim dgc_title As New BoundColumn() dgc_title.DataField = "title" dgc_title.HeaderText = "Title" DataGrid1.Columns.Add(dgc_title) Me.DataGrid1.DataBind() Me.DynamicColumnAdded = True End Sub
// C# private bool DynamicColumnAdded{ get { object b = ViewState["DynamicColumnAdded"]; return (b == null) ? false : true; } set { ViewState["DynamicColumnAdded"] = value; } }
this.sqlDataAdapter1.Fill(this.dsBooks1); DataGrid1.DataBind(); this.DynamicColumnAdded = true; } Adding New Records to a Data Source Using the DataGrid Control The DataGrid control allows users to view and edit records, but does not inherently include the facility to add new ones. However, you can add this functionality in various ways, all of which involve the following: