DropDownList在绑定数据源控件后,该如何设置选中项呢
我按以下方法未能实现,我的代码如下:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1"
DataTextField="subject" DataValueField="id" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
![]()
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:strconn %>"
SelectCommand="SELECT [id], [subject] FROM [web_about]"></asp:SqlDataSource>
CS文件中来设置选中项:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id=Request.QueryString["id"];
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(id));
}
}
![]()
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(Request.Path + "?id=" + DropDownList1.SelectedItem.Value);
}
但以上的方法在不绑定数据源的情况下正常:
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Value="1">选项一</asp:ListItem>
<asp:ListItem Value="2">选项二</asp:ListItem>
</asp:DropDownList>
由于初学.NET,不知是什么原因?
我按以下方法未能实现,我的代码如下:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1"
DataTextField="subject" DataValueField="id" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:strconn %>"
SelectCommand="SELECT [id], [subject] FROM [web_about]"></asp:SqlDataSource>CS文件中来设置选中项:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(id));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(Request.Path + "?id=" + DropDownList1.SelectedItem.Value);
}<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem Value="1">选项一</asp:ListItem>
<asp:ListItem Value="2">选项二</asp:ListItem>
</asp:DropDownList>
由于初学.NET,不知是什么原因?
