DropDownListBoundColumn for ASP.Net Datagrid
Use code such as the following to add the column to your grid:
Dim t As New System.Web.UI.WebControls.TemplateColumn With t .HeaderText = "Col Header" .ItemTemplate = New MyDropDownTemplate("DataField", TRUE) 'displaying items Is always read only .EditItemTemplate = New MyDropDownTemplate("ActionRequired", FALSE) .Visible = TRUE End With MyDataGrid.Columns.Add(t)
The following class is the implemantation of ITemplate that creates the dropdown column. This example is a column that has true/false values only.
Public Class MyDropDownTemplate Implements ITemplate Private m_data As String Private m_read As Boolean Public Sub New(ByVal DataSource As String, ByVal [ReadOnly] As Boolean) m_data = DataSource m_read = [ReadOnly] End Sub Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn If m_read Then Dim l As New System.Web.UI.WebControls.Literal AddHandler l.DataBinding, AddressOf Me.DataBind container.Controls.Add(l) Else Dim dl As New System.Web.UI.WebControls.DropDownList AddHandler dl.DataBinding, AddressOf Me.DataBind 'now add the items To the list dl.Items.Add("True") dl.Items.Add("False") container.Controls.Add(dl) End If End Sub Private Sub DataBind(ByVal sender As System.Object, ByVal e As System.EventArgs) If m_read Then Dim l As System.Web.UI.WebControls.Literal = CType(sender, System.Web.UI.WebControls.Literal) Dim container As DataGridItem = CType(l.NamingContainer, DataGridItem) Dim DRV As DataRowView = CType(container.DataItem, DataRowView) l.Text = CType(DRV(m_data), String) Else Dim dl As System.Web.UI.WebControls.DropDownList = CType(sender, System.Web.UI.WebControls.DropDownList) Dim container As DataGridItem = CType(dl.NamingContainer, DataGridItem) Dim DRV As DataRowView = CType(container.DataItem, DataRowView) 'determine the selected item If CType(DRV(m_data), String).ToLower = "true" Then dl.SelectedIndex = 0 Else dl.SelectedIndex = 1 End If End If End Sub End Class