大家好我有一个关于如何将项目添加到具有某些属性的下拉列表的问题。我的第一个想法是:
<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>
在代码中:
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
元素在下拉列表中正确包含,但仅包含text属性。选中的值不起作用。您认为我做错了什么,或者我可以通过其他方式轻松地做到这一点吗?
感谢一百万人的帮助
答案 0 :(得分:1)
如果在GridView中使用DropDownList,则用数据填充它们的最简单方法是使用OnRowDataBound
事件。
<asp:GridView ID="GV_Area" runat="server" OnRowDataBound="GV_Area_RowDataBound">
背后的代码
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