我经常使用此代码为gridview中的按钮,复选框,标签等创建模板字段:
<asp:TemplateField HeaderText="Data_1" ShowHeader="False" Visible="True">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CommandName="Button1_Command" CssClass="round_button"
Height="20px" Width="20px" />
</ItemTemplate>
</asp:TemplateField>
但这一次,带复选框的列数不确定。 (我需要在数据库中提取某些数据以确定我需要多少个复选框列)。如何在页面加载时以编程方式创建复选框列?
谢谢:)
答案 0 :(得分:0)
希望以下代码可以帮助您。这不是一个完整的代码,但它会给你提示或想法如何创建programmaticaly复选框列。谢谢。
<asp:GridView runat="server" ID="grdView">
<Columns>
<asp:TemplateField HeaderText="Button" ShowHeader="False" Visible="True">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CommandName="Button1_Command" CssClass="round_button"
Height="20px" Width="20px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Public Class _Default
Inherits Page
Public Class GridViewCustomColumn
Public Property ColumnName As Boolean
Public Property HeaderName As String
End Class
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim lists As New List(Of GridViewCustomColumn) From { _
New GridViewCustomColumn() With {.ColumnName = False, .HeaderName = "TestHeaderName1"}, _
New GridViewCustomColumn() With {.ColumnName = True, .HeaderName = "TestHeaderName2"}}
grdView.AutoGenerateColumns = False
Dim templateField As New TemplateField()
templateField.ItemTemplate = New CheckBoxTemplateImpl("ColumnName")
grdView.Columns.Add(templateField)
grdView.DataSource = lists
grdView.DataBind()
End Sub
Public Class CheckBoxTemplateImpl
Implements ITemplate
Public Property ColumnName As String
Public Sub New(columnName As String)
Me.ColumnName = columnName
End Sub
Public Sub InstantiateIn(container As Control) Implements ITemplate.InstantiateIn
Dim chkBox As New CheckBox()
AddHandler chkBox.DataBinding, AddressOf chkBox_DataBinding
container.Controls.Add(chkBox)
End Sub
Private Sub chkBox_DataBinding(sender As Object, args As EventArgs)
Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
Dim gridViewRow As GridViewRow = DirectCast(chkBox.NamingContainer, GridViewRow)
Dim bindValue As Object = DataBinder.Eval(gridViewRow.DataItem, ColumnName)
If bindValue IsNot Nothing Then
chkBox.Text = bindValue.ToString()
End If
End Sub
End Class
End Class