有一个无效 SelectedValue
1、创建一个textbox控件,指定ID为xxx_save,xxx为dropdownlist的ID,这不是规则,是写代码的习惯而已。将该textbox的Visible属性设为false,它只作为存值控件。
2、给dropdownlist添加SkinID并指向textbox,同时给textbox添加SkinID指向dropdownlist。
3、给dropdownlist添加OnSelectedIndexChanged方法
给textbox添加OnDataBinding方法
如下
<asp:DropDownList ID="drop_list" runat="server"
SkinID="drop_list_save" OnSelectedIndexChanged="drop_list_onchange"
DataSourceID="bind_data"
DataTextField="text"
DataValueField="value">
</asp:DropDownList>
<asp:SqlDataSource ID="bind_data" runat="server"
ConnectionString="<%$ ConnectionStrings:dbname %>"
SelectCommand="SELECT * FROM [table]">
</asp:SqlDataSource>
<asp:TextBox ID="drop_list_save" runat="server" Visible="false" SkinID="drop_list" OnDataBinding="drop_list_onbinding" Text='<%#Bind("xxx") %>'>
</asp:TextBox>
4、在后台代码中添加两个方法
protected void drop_list_onchange(object sender, EventArgs e) {
DropDownList ddl = (DropDownList)sender;
TextBox tb = (TextBox)ddl.Parent.FindControl(ddl.SkinID);
tb.Text = ddl.SelectedValue;
}
protected void drop_list_onbinding(object sender, EventArgs e) {
TextBox tb = (TextBox)sender;
DropDownList ddl = (DropDownList)tb.Parent.FindControl(tb.SkinID);
try{
ddl.SelectedValue = tb.Text;
}catch(Exception){
}
}
5、如上方法的意思是将前台出现的BUG,在后台获取,并不予处理,这样就避免页面报错了。同时也实现了dropdownlist的数据与表单数据绑定。如果出现空值问题,页面会将dropdownlist的值置为列表第一项。问题解决!