yongshi123

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
First, this individual's XML file looked like this:
<?xml version="1.0" encoding="utf-8" ?>
<companytype>
<option value="Agricultural" name="Agricultural" />
<option value="Apparel" name="Apparel" />
<option value="Beverages" name="Beverages" />
<option value="Building Products" name="Building Products" />
</companytype>
Obviously, this looks more like the HTML you'd have in the actual listbox itself, and doesn't lend itself well to databinding. So the first thing I did was rewrite the XML so that it could be loaded into a DataSet and used more efficiently. Following is the revised code for "Xmldroplist.xml":
<?xml version="1.0" encoding="utf-8" ?>
<companytypes>
<companytype>
<value>Agricultural</value>
<name>Agricultural</name>
</companytype>
<companytype>
<value>Apparel</value>
<name>Apparel</name>
</companytype>
<companytype>
<value>Beverages</value>
<name>Beverages</name>
</companytype>
<companytype>
<value>Building Products</value>
<name>Building Products</name>
</companytype>
</companytypes>
Finally, I pieced together the most basic code to create the server control on the page, load the XML into a DataSet, and use dynamic databinding to populate the dropdown listbox. Following is the code for "XMLDropDownList.aspx":
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.XPath" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<%@ Import Namespace="System.IO" %>
<script language="C#" runat="Server">
void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
BindDropDown();
}
}

void BindDropDown() {
string url = "http://localhost/ASP.NET/xmldroplist.xml";
DataSet ds = new DataSet();
ds.ReadXml(url);
customers.DataSource =ds.Tables[0];
customers.DataTextField =ds.Tables[0].Columns[0].ToString();
customers.DataValueField=ds.Tables[0].Columns[1].ToString();
customers.DataBind();
// Next 2 lines show way to set select item text and value...
//customers.Items.Insert(0, new ListItem("TestValue")) ;
//customers.Items[0].Value="84";
// Next line shows another way but using an existing item...
// customers.SelectedIndex=2;

}
</script>
<html>
<body bgcolor="#ffffff">
<form runat="server" ID="Form1">
<b>Select a Company Type to View:</b>
<asp:DropDownList id="customers" runat="server" />
</form>
</body>
</html>
When you run this page you'll get your dropdown listbox with all the values in it, and if you view source you'll see that both the DataTextField and the DataValueField properties have been translated into their proper places in each <option> element.
posted on 2008-10-20 11:22  yongshi123  阅读(440)  评论(0编辑  收藏  举报