DropDownlist的Item显示多列数据
前一次,在数据库绑定好需要显示的字段。这链接可参考到原来实现的方法:http://www.cnblogs.com/insus/articles/2075101.html
此次,Insus.NET想使用另外一种方法来实现它。使用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>
<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 数据类型:
View Code
private DataTable DataSource()
{
DataSet objDs = new DataSet();
objDs.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/Users.xml"));
return objDs.Tables[0];
}
{
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>
</asp:DropDownList>
在aspx.cs为DropDownList控件绑定数据:
View Code
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();
}
{
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组合为一个字衔串。
GetFullName
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;
}
{
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"事件:
View Code
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));
}
}
{
var ddl = sender as DropDownList;
foreach (ListItem li in ddl.Items)
{
li.Text = string.Format("{0}", GetFullName(li.Value));
}
}
可从下面图片看到实现前后对比效果: