【问题标题】:Displaying one column of data from a 2d array into a combobox将二维数组中的一列数据显示到组合框中
【发布时间】:2017-04-27 15:40:02
【问题描述】:

我正在尝试从二维数组中取出一列并将其显示到组合框中。我用于二维数组的文本文件中的数据在这里,我想在组合框中显示 1001、1010、1003 和 1005 作为选项,然后根据他们选择的选项显示其余的列表框中的数据:

1001,55000,46326.26,7,30,352.61
1010,30000,11757.26,5,15,228.61
1003,1000,406.35,5,1,82.49
1005,5000,2042.72,3,2,207.09

到目前为止,我已经声明了数组并从文本文件中加载了数据:

public Form1()
{
    InitializeComponent();
}
string[,] loans = new string[4, 6];
int recordCount = 0;


private void Form1_Load(object sender, EventArgs e)
{
    string currentLine;
    string[] fields = new string[6];
    int row = 0;
    StreamReader loanReader = new StreamReader(@"C:\loans.txt");
    while (loanReader.EndOfStream == false)
    {
        currentLine = loanReader.ReadLine();
        fields = currentLine.Split(',');
        loans[row, 0] = fields[0];
        loans[row, 1] = fields[1];
        loans[row, 2] = fields[2];
        loans[row, 3] = fields[3];
        loans[row, 4] = fields[4];
        loans[row, 5] = fields[5];
        row = row + 1;
    }
    recordCount = row;
    loanReader.Close();
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}

如何只挑出要显示在组合框中的第一列?

【问题讨论】:

    标签: c# arrays winforms combobox


    【解决方案1】:

    您可以在第一列上循环并将每个值添加到 combobox

    int nbrRows = 4;
    
    for(int i = 0; i < nbrRows; i++)
    {
        comboBox1.Items.Add(loans[i, 0]);
    }
    

    然后当他们在组合框中选择一个值时

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int row = comboBox1.SelectedIndex;
    
        for(int i = 0; i < nbrColumns; i++)
        {
            listBox1.Items.Add(myArray[row, i]);
        }
    
    }
    

    您可以使用SelectedIndex 获取选择了哪个索引,它会告诉您必须添加哪一行。然后根据 nbrColumns 的列数(在您的情况下为 6)在该行中循环,并将它们添加到列表框中。

    您可能还想在comboBox1_SelectedIndexChanged的开头添加

    listBox1.Items.Clear();
    

    如果您不想保留旧值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多