DropDownList Datagrid

flann

Freshman
Joined
Aug 16, 2005
Messages
33
I have my datagrid working now, but I'm trying to add a dropdownlist with just a few items in it to my editable datagrid. I've searched online, and what I found seems very involved, is there an easy way?
 
It is fairly involved. You do it using templates. personally I don't like using pseudohtml templates in aspx pages - I like to build my own template classes. Here is an example of one I made to show either true or false in a dropdown on edit:

Visual Basic:
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

You then add the column to your datagrid using:

Visual Basic:
Dim t As New System.Web.UI.WebControls.TemplateColumn 
With t 
    .HeaderText = "Col Header" 
    .ItemTemplate = New MyDropDownTemplate("DataFieldName", True) 'displaying items is always read only
    .EditItemTemplate = New MyDropDownTemplate("DataFieldName", False) 
    .Visible = True 
End With 
.Columns.Add(t)

:)
 
Back
Top