一、用法
一般情况下,我们使用下拉框,无非两个意图。1.直接获取字面值。2.字面值只是为了显示,我们需要得到代表该字面值的编码。对于服务器控件DropDownList这两点都能满足。如下演示将表格数据绑定到下拉框
上代码:
#region 数据源绑定
//下拉框绑定(通过datatable
private void DataBindDropDownList(DropDownList downlist, DataTable dt,string displayFiled,string ValueFiled)
{
downlist.Items.Clear();
downlist.DataSource = dt;
downlist.DataTextField = displayFiled;//指定字面值,即显示给用户看的值(指定为dt之中列名)
downlist.DataValueField = ValueFiled;//指定背后的编码(指定为dt之中的列名)
downlist.DataBind();
}
#endregion
如果取出选中值:
string displayFiled= sys_provider_code.SelectedValue;//sys_provider_code为一下拉框
二、注意
如果我们在网页加载的时候,初始化下拉框的方式不对,会导致即使选中了下拉框的某个值,依然每次都获取不到我们所要的值,得到的只是默认的第一个值。
错误写法:
protected void Page_Load(object sender, EventArgs e)
{
this._key = base.Request["key"];
DataBindDropDownList(sys_provider_code, (new DataExport()).GetDataByCondition(SqlDic_Provider), "provider_name", "provider_code");
DataBindDropDownList(sys_org_code, (new DataExport()).GetDataByCondition(SqlDic_Org), "org_name", "org_code");
if (!base.IsPostBack)
{
if (!string.IsNullOrEmpty(this._key))
{
this.InitData();
}
}
}
这样写,每次得到的都是默认第一个的值。
正确写法:
protected void Page_Load(object sender, EventArgs e)
{
this._key = base.Request["key"];
if (!base.IsPostBack)
{
DataBindDropDownList(sys_provider_code, (new DataExport()).GetDataByCondition(SqlDic_Provider), "provider_name", "provider_code");
DataBindDropDownList(sys_org_code, (new DataExport()).GetDataByCondition(SqlDic_Org), "org_name", "org_code");
if (!string.IsNullOrEmpty(this._key))
{
this.InitData();
}
}
}
这样才算可以。