如何在 c# 中加载页面时在下拉列表中设置默认值 - asp.net
本文关键字:设置 默认值 asp net 下拉列表 加载 | 更新日期: 2023-09-27 18:35:59
我在aspx页面中创建了两个下拉列表
<div class="row-form">
<div class="span3">
Line of Authority <span class="RequiredField">* </span>:
</div>
<div class="span3">
<asp:DropDownList ID="drpLineOfAuthority" AutoPostBack="true" onselectedindexchanged="drpJurisdiction_SelectedIndexChanged" runat="server"></asp:DropDownList>
<!-- <tpLineOfAuthority:ctLineOfAuthority ID ="chkLineOfAuthority" runat="server" /> -->
</div>
<div class="clear">
</div>
</div>
<div class="row-form">
<div class="span3">
State <span class="RequiredField">* </span>:
</div>
<div class="span3">
<asp:DropDownList ID="drpJurisdiction" AutoPostBack="true" onselectedindexchanged="drpJurisdiction_SelectedIndexChanged" runat="server"></asp:DropDownList>
</div>
在 aspx 中.cs文件
as protected override void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (urlAction != URLAction.update)
{
FillDropDown();
}
}
}
private void FillDropDown()
{
JurisdictionBL jbl;
jbl = new JurisdictionBL(0);
DataSet ds = new DataSet();
jbl.FetchAll(ds);
...
...
if (urlAction != URLAction.update)
{
drpJurisdiction.SelectedValue = "--Please select any state--";
drpLineOfAuthority.SelectedValue = "--Please select LOA--";
}
}
请注意,FillDropDown() 函数正在用值填充下拉列表项,这些值是从数据库中检索的。
现在的问题是上面的代码没有为下拉列表设置默认值!!请帮帮我!!
尝试这样做,它会起作用
drpJurisdiction.Items.Insert(0, new ListItem("--Please select any state--", "0"));
这是因为数据库中的列表不包含字符串"--请选择任何状态--"和"--请选择LOA--",请确保源数据表中具有默认值。
例如,如果数据表 DT 具有从数据库中检索的值,则可以在运行时将默认值添加为新行
DataRow DR = DT.NewRow();
DR[0] = "--Please select LOA--";
DT.Rows.InsertAt(DR, 0);
尝试探索AppendDataBoundItems
属性。
<asp:DropDownList ID="drpJurisdiction" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Please select any state--" Value="" />
</asp:DropDownList>
确保AppendDataBoundItems
设置为 true,否则在代码隐藏中绑定数据时将清除该。
交互
<asp:DropDownList runat="server" ID="drpJurisdiction" ondatabound="OndrpJurisdictionDataBound"></asp:DropDownList>
然后在您的代码隐藏中:
protected void OndrpJurisdictionDataBound(object sender, EventArgs e)
{
drpJurisdiction.Items.Insert(0, new ListItem("--Please select any state--", ""));
}