Saturday, March 03, 2007

ListBox tricky to set in a DataGrid/GridView

Listboxes are very tricky to set selected items in grid - there is no real nice way to do it. It would have been great if Microsoft included a property that accepts an array or comma separated values - or anything! But they only allow each item in the list to be selected individually. The way to do this in a grid is a bit messy, but it is fairly simple to implement. When a row is created (as per the event), select the items of the listbox as per the datagrid source data:

HTML code:
<asp:listbox id="listBox" DataSource="<%# dtCase_Type %>" runat="server" selectionmode="Multiple" datasource="" datavaluefield="Code" datatextfield="Description">

VB code behind:
Private Sub myDataGrid_Itembound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles myDataGrid.ItemDataBound
If e.Item.ItemType = ListItemType.EditItem Then
Dim intRow As Integer = CInt(e.Item.ItemIndex)
If Not IsDBNull(datatableCache.Rows(intRow)("DataFieldFromDataStore")) Then
'datatableCache.Rows(intRow)("DataFieldFromDataStore") contains the list of values (in this case comma seperated)
Dim aryValues() As String = datatableCache.Rows(intRow)("DataFieldFromDataStore").ToString.Split(","c)
Dim listBox As ListBox = e.Item.FindControl("listBox")
For Each li As ListItem In listBox.Items
If Array.IndexOf(aryValues, li.Value) > -1 Then li.Selected = True
Next
End If
End If
End Sub

1 comment:

RN said...

i have found a simple way to select the value of a listbox control within a gridview.
you can simply handle the RowDataBound event of the gridview. using the GridViewRowEventArgs.Row.FindControl method, you can find the listbox control within the row. The corresponding datarow can be accessed using the GridViewRowEventArgs.Row.DataItem object. this returns an instance of the DataRowView class. it works similar to the DataRow, i guess.

i hope the following code helps.


Private Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
Dim tmpList As ListBox = CType(e.Row.FindControl("Listbox1"), ListBox)
If Not tmpList Is Nothing Then
Dim drData As DataRowView = e.Row.DataItem
If Not IsDBNull(drData("Table_Field")) Then tmpList.SelectedValue = drData("Table_Field")
End If
End Sub