problem with databinding xml list to asp.net dropdownlist
I have this xml file, and now i will want to add new entries to my xml file
Before:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
</builder>
</builderemail>
<managerem开发者_运维百科ail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
</manager>
</manageremail>
</email>
After:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
<id>2</id>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
<id>2</id>
<value>Others</value>
</manager>
</manageremail>
</email>
my code c# codes:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Visible = false;
Button1.Visible = false;
TextBox2.Visible = false;
Button2.Visible = false;
if (!IsPostBack)
{
PopulateDDLFromXMLFile();
}
}
public void PopulateDDLFromXMLFile()
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/builderemail.xml"));
//get the dataview of table "Country", which is default table name
DataView dv = ds.Tables["builder"].DefaultView;
DataView dw = ds.Tables["manager"].DefaultView;
//or we can use:
//DataView dv = ds.Tables[0].DefaultView;
//Now sort the DataView vy column name "Name"
dv.Sort = "value";
//now define datatext field and datavalue field of dropdownlist
DropDownList1.DataTextField = "value";
DropDownList1.DataValueField = "ID";
DropDownList2.DataTextField = "value";
DropDownList2.DataValueField = "ID";
//now bind the dropdownlist to the dataview
DropDownList1.DataSource = dv;
DropDownList1.DataBind();
DropDownList2.DataSource = dw;
DropDownList2.DataBind();
}
However, this does not work. I will get a IndexOutOfRangeException error. how do i handle this?
The "IndexOutOfRange" exception is because of this line of code:
dv.Sort = "value"; //because the Table "builder" doesn't have the "value" column
The method PopulateDDLFromXMLFile works with the first version of xml. The later version of xml is not a valid one and doesn't represent what you want to / trying to do in PopulateDDLFromXMLFile method.
DataSet ds = new DataSet();
ds.ReadXml(MapPath("~/App_Data/builderemail.xml"));
Calling above code on the newer xml creates 6 tables, one for builderemail, builder, id, value, manageremail and manager.
But the code assumes that id and value would be columns inside builder table. Hence the above exception.
I would suggest you modify the xml as:
<?xml version="1.0" encoding="utf-8" ?>
<email>
<builderemail>
<builder>
<id>1</id>
<value>builder@xyz.com</value>
</builder>
<builder>
<id>2</id>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<id>1</id>
<value>manager@xyz.com</value>
</manager>
<manger>
<id>2</id>
<value>Others</value>
</manger>
</manageremail>
</email>
精彩评论