我正在使用ASP.NET,我在网格中有一个下拉列表(radGrid)。
我喜欢发生的是当下拉列表出现时,我喜欢它默认为 “请选择”仅当其绑定的字段为空时。另外,我喜欢从DataSource获取值。
我有以下代码:
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
对于DataSource,这里是代码:
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
以下是代码隐藏中的代码:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
当它执行Binding时,如果值为空,则会收到错误消息,指出它无法找到该值。
答案 0 :(得分:0)
为此使用Grid PreRender事件。您可能需要将值分配给某个隐藏标签并在prerender方法中访问它并将其分配给下拉列表。
<ItemTemplate>
<asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" />
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
</ItemTemplate>
关于代码背后:
protected void GridView1_PreRender(object sender, EventArgs e)
{
for(int i=0;i<Gridview1.Rows.Count;i++)
{
Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue');
DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup');
ddl.Items.Insert(0, new ListItem("Please Select", ""));
if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text))
ddl.SelectedValue = lblValue.Text;
}
}
答案 1 :(得分:0)
尝试:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list.Items.Count.equals(0))
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}