从XML文件中读取数据绑定到DropDownList

本文介绍了一种使用ASP.NET中DropDownList控件的方法,通过从XML文件读取数据并将其绑定到DropDownList中,实现了动态填充下拉列表的功能。示例包括创建数据源、配置Web.config以及使用C#进行绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

using System.Xml;
using System.Collections;

1 、绑定DropDownList:

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.DataSource 
= createDataSource();
    DropDownList1.DataTextField 
= "languageTextField";
    DropDownList1.DataValueField 
= "languageValueField";
    DropDownList1.DataBind();
}

 

2、上面用到的createDataSource()方法: 

private ICollection createDataSource()
{
    
//create a data table to store the data for the ddl_langauge control
    DataTable dt = new DataTable();
    
//define the columns of the table
    dt.Columns.Add("languageTextField"typeof(string));
    dt.Columns.Add(
"languageValueField"typeof(string));
    
//read the content of the xml file into a DataSet
    DataSet lanDS = new DataSet();
    
string filePath = Server.MapPath(ConfigurationManager.AppSettings["LanguageXmlFile"].ToString());
    lanDS.ReadXml(filePath);
    
if (lanDS.Tables.Count > 0)
    {
        
foreach (DataRow copyRow in lanDS.Tables[0].Rows)
        {
            dt.ImportRow(copyRow);
        }
    }
    DataView dv 
= new DataView(dt);
    
return dv;
}

 

3、Web.config

<configuration>
    
<appSettings>
    
<!--The file path for the language type xml file-->
    
<add key="LanguageXmlFile" value="Languages.xml"/>    
  
</appSettings>
<connectionStrings/>

 

4、Languages.xml 

<?xml version="1.0" encoding="gb2312"?>
<languageTypes>
   
<language>
      
<languageValueField>en-US</languageValueField>
      
<languageTextField>English</languageTextField>
   
</language>
   
<language>
      
<languageValueField>zh-CN</languageValueField>
      
<languageTextField>中文</languageTextField>
   
</language>
   
<language>
      
<languageValueField>ja-JP</languageValueField>
      
<languageTextField>日语</languageTextField>
   
</language>
</languageTypes>

 

code down

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值