Reputation: 462
Hi all I have a question about how can I add Items to a dropdownlist with some attributes. My first Idea was:
<asp:GridView ID="GV_Area" runat="server" AutoGenerateColumns="false" CssClass="table table-striped bolsa-table-gv text-center"
DataKeyNames="Area,Oferta">
<Columns>
<asp:BoundField DataField="Nombre" HeaderText="Nombre" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddl_Especializaciones" runat="server" CssClass="selectpicker" multiple DataSource='<%#GetDropDownData(Container)%>'></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the code:
Protected Function GetDropDownData(e As System.Web.UI.WebControls.GridViewRow) As ListItem()
Dim item As ListItem = New ListItem
Dim arr As ArrayList = New ArrayList
item.Selected = True
item.Text = "Hello"
item.Value = "Hello2"
arr.Add(item)
Return arr
End Function
The elements are included correctly in the dropdownlist but only with the text attribute. The selected and the value is not working. What do you think I'm doing wrong or, can I do it easily in another way?
Thanks a million for the help
Upvotes: 0
Views: 74
Reputation: 35514
If you use the DropDownList in a GridView, the easiest way to fill them with data is to use the OnRowDataBound
event.
<asp:GridView ID="GV_Area" runat="server" OnRowDataBound="GV_Area_RowDataBound">
Code behind
Protected Sub GV_Area_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
'check if the row is a datarow
If (e.Row.RowType = DataControlRowType.DataRow) Then
'cast the row back to a datarowview
Dim row As DataRowView = CType(e.Row.DataItem,DataRowView)
'use findcontrol to locate the dropdownlist
Dim ddl As DropDownList = CType(e.Row.FindControl("ddl_Especializaciones"),DropDownList)
'if you need to use a datasource value for filling the dropdownlist
Dim Nombre As Integer = Convert.ToInt32(row("Nombre"))
'now fill the dropdownlist with values
'from a datasource, where 'textField' and `valueField` are colums/properties of the datasource
ddl.DataSource = Common.LoadFromDB
ddl.DataTextField = "textField"
ddl.DataValueField = "valueField"
ddl.DataBind
'or add them manually
ddl.Items.Insert(0, New ListItem("Item A", "1", true))
ddl.Items.Insert(1, New ListItem("item B", "1", true))
End If
End Sub
Upvotes: 1