asp.net c# txt file to dropdownlist:



我需要用一个txt文件填充一个下拉列表。我试过了,但不起作用。

protected void DropDownListCOUNTRY_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> country = new List<string>();
country = File.ReadAllLines("../App_Data/txt/CountryList.txt").Select(x => x.Split('_')[0]).ToList();
foreach (string countrysingle in country)
{
DropDownListCOUNTRY.Items.Add(new ListItem(countrysingle, countrysingle));
}
}

这是在C#中工作的VB代码

if (this.IsPostBack == false) 
{
string path = MapPath("~/App_Data/txt/CountryList.txt");
FileStream fp = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fp);
string data;
while ((data = reader.ReadLine()) != null)
{
string[] v = data.Split(',');
foreach (string entry in v)
{
DropDownListCOUNTRY.Items.Add(entry);
}
}
reader.Close();
fp.Close();
}

我第一个问题中的VB代码有效。

我认为您还必须在foreach循环中给出变量声明,就像下面的一样

foreach (string countrysingle in country) { 
DropDownListCOUNTRY.Items.Add(countrysingle); 
}

最新更新