使用OnDataBound事件重写它的Text绑定。
数据源是一个XML文件,放在Web 程序的App_Data目录下:
Users <? xml version="1.0" encoding="utf-8" ?>< users >
< user >
< id >0 </ id >
< FirstName >Johe </ FirstName >
< LastName >Li </ LastName >
</ user >
< user >
< id >1 </ id >
< FirstName >Michael </ FirstName >
< LastName >Zhang </ LastName >
</ user >
< user >
< id >2 </ id >
< FirstName >Mary </ FirstName >
< LastName >ping </ LastName >
</ user >
</ users >
写一个方法,获取数据,返回一个DataTable 数据类型:
private DataTable DataSource(){
DataSet objDs = new DataSet();
objDs.ReadXml(HttpContext.Current.Server.MapPath( " ~/App_Data/Users.xml "));
return objDs.Tables[ 0];
}
aspx:
View Code < asp:DropDownList ID ="DropDownList1" runat ="server" OnDataBound ="DropDownList1_DataBound1" ></ asp:DropDownList >
在aspx.cs为DropDownList控件绑定数据:
protected void Page_Load( object sender, EventArgs e){
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.DropDownList1.DataSource = DataSource();
this.DropDownList1.DataTextField = " FirstName ";
this.DropDownList1.DataValueField = " id ";
this.DropDownList1.DataBind();
}
现在我们还要写一个函数,参数为传入记录的id,即是DropDownList的DataValueField,返回Firstname与Lastname组合为一个字衔串。
private string GetFullName( string id){
string ln = string.Empty;
foreach (DataRow dr in DataSource().Rows)
{
if ( string.Compare(dr[ " id "].ToString(),id) == 0)
{
ln = dr[ " FirstName "].ToString() + " " + dr[ " LastName "].ToString();
break;
}
}
return ln;
}
最后,我们还要实现OnDataBound="DropDownList1_DataBound1"事件:
protected void DropDownList1_DataBound1( object sender, EventArgs e){
var ddl = sender as DropDownList;
foreach (ListItem li in ddl.Items)
{
li.Text = string.Format( " {0} ", GetFullName(li.Value));
}
}