2015-08-20 50 views
2

我試圖完成以下任何幫助。我如何獲得1列表的值取決於另一個列表的值

我有一個CSV文件,其中包含2列,1名稱列表和其他關聯的ID列表。

例如,
的Test1,00001
的Test2,00002

我已閱讀這些到我的程序分爲2名列表。 1. nameList 2. idList

我已經使用nameList的值填充了組合框的數據源。

現在,當在組合框中選擇一個名稱並按下一個按鈕時,我想獲得該ID。所以如果Test1被選中,當按下按鈕時00001被返回,就好像Test2被選中並且按鈕被按下,00002被返回。

如果它有幫助,這是我目前用來填充列表。

public void nameCSV() 
    { 
     var reader = new StreamReader(File.OpenRead(@"C:\temp\nameList.csv")); 
     List<string> nameList = new List<string>(); 
     List<string> idList = new List<string>(); 
     while (!reader.EndOfStream) 
     { 
      var line = reader.ReadLine(); 
      var values = line.Split(','); 

      nameList.Add(values[0]); 
      idList.Add(values[1]); 
     } 
     cmbxName.DataSource = releaseNameList; 
    } 
+0

在這個_particular_ context中,您可以簡單地使用'idList [cmbxName.SelectedIndex]'。 (編輯:一定要檢查'SelectedIndex == -1',因爲這表明沒有選擇任何東西,如果你使用它會導致錯誤)但是,考慮創建一個簡單的類來定義一個名稱 - ID對,在這裏做的是[基本上是反模式]。(http://codeblog.jonskeet.uk/2014/06/03/anti-pattern-parallel-collections/) –

+0

告訴我,如果你不明白我的東西回答! – mybirthname

回答

0
public void nameCSV() 
{ 
    var reader = new StreamReader(File.OpenRead(@"C:\temp\nameList.csv")); 

    DataTable tbl = new DataTable(); 
    tbl.Columns.Add("Name", typeof(string)); 
    tbl.Columns.Add("ID", typeof(string)); 

    while (!reader.EndOfStream) 
    { 
     var line = reader.ReadLine(); 
     var values = line.Split(','); 

     DataRow row = tbl.NewRow(); 
     row["Name"]=values[0]; 
     row["ID"] = values[1]; 
     tbl.Rows.Add(row); 
    } 

    cmbxName.DisplayMember = "Name"; 
    cmbxName.ValueMember = "ID"; 

    cmbxName.DataSource = tbl; 


} 

你需要類似的東西。檢查組合框的DisplayMember和ValueMember屬性。

所以,當按鈕被點擊,你想採取價值而不是顯示文本。

protected void Button1_Click(object sender, EventArgs e) 
{ 
     string id = cmbxName.SelectedValue; 
} 

N.B:Your title is misleading!

0

使用Dictionary

public void nameCSV() 
{ 
    var reader = new StreamReader(File.OpenRead(@"C:\temp\nameList.csv")); 
    Dictionary<string, int> userDict = new Dictionary<string, int>(); 
    while (!reader.EndOfStream) 
    { 
     var line = reader.ReadLine(); 
     var values = line.Split(','); 

     userDict.Add(values[0], values[1]); 
    } 
    cmbxName.DataSource = userDict; 
} 

打電話給定用戶ID的值只是使用的關鍵。例如'Test1'

string Username = "Test1"; 
int userid; 
userid = userDict[Username]; 

有一點需要注意的是,字典可以更好地使用數值作爲鍵,而不是字符串。在你的情況下,你正在查找字符串名稱,所以它應該是這樣的。只要字符串長度很短 - 不能超過10個字符。性能明智,你應該沒問題。

相關問題