I'm dynamically adding columns to a GridView which contains two declaratively-defined TemplateFields which each contain a LinkButton. When I add the new columns after the TemplateColumns, everything works fine. But when I insert the columns into the beginning of the GridView's columns collection, all of the TemplateFields disappear when I click on one of the LinkButtons!
What's going on here?
Thanks in advance for whatever help you can provide,
-Justin
What's going on here?
Thanks in advance for whatever help you can provide,
-Justin
Code:
<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="test.aspx.vb" Inherits="test" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="lblCommandName" runat="server" Text="(Command name)"></asp:Label>
<asp:GridView runat="server" ID="myGridView" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btnSomething" runat="server" CausesValidation="False" CommandName="Something"
Text="Do something"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btnSomethingElse" runat="server" CausesValidation="False" CommandName="Something else"
Text="Do something else"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
Code:
Imports System.Data
Partial Class test
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim ds As New DataSet()
Dim dt As New DataTable("tbl")
dt.Columns.Add(New DataColumn("data", GetType(String)))
dt.Rows.Add("abc")
dt.Rows.Add("123")
ds.Tables.Add(dt)
myGridView.DataSource = ds
Dim field As New BoundField()
field.DataField = "data"
'This works:
myGridView.Columns.Add(field)
'But this doesn't:
myGridView.Columns.Insert(0, field)
myGridView.DataBind()
End If
End Sub
Protected Sub myGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles myGridView.RowCommand
lblCommandName.Text = e.CommandName
End Sub
End Class