【问题标题】:C# populating 2 combo boxes and 1 text box with values from a txt file with only 1 selectionC# 使用 txt 文件中的值填充 2 个组合框和 1 个文本框,只有 1 个选择
【发布时间】:2019-09-03 09:05:18
【问题描述】:

我有一个文本文件,其中有 3 个用逗号分隔的“列”,

我可以将它们单独加载到每个组合框或文本框中

我想要做的是只从nameComboBox 中选择第一列的值,然后用同一行的值自动填充其他两个框。

另外,如果我可以改进将最后一列放入组合框然后放入文本框的方式。

另外考虑一下,我可以将numberComboBoxdescriptionComboBox 都更改为文本框,因为它们不会被选择?

文本文件(notes.txt):

run, 1, runs the file
save, 2, saves the file
delete, 3, deletes the file

当前代码:

    public Main()
    {
        InitializeComponent();
        string[] notes = File.ReadAllLines("C:\\notes.txt");
        foreach (var line in notes)
        {
            string[] tokens = line.Split(',');
            nameComboBox.Items.Add(tokens[0]);
            numberComboBox.Items.Add(tokens[1]);
            descriptionComboBox.Items.Add(tokens[2]);
        }

        descriptionComboBox.Text = descriptionTextBox.Text;
    }

例如,如果我从nameComboBox 中选择run,我希望numberComboBox 填充2descriptionComboBox 填充deletes the file

更好的是我从nameComboBox 中选择run 我希望numberTextBox 填充2descriptionTextBox 填充deletes the file

【问题讨论】:

    标签: c# combobox textbox text-files


    【解决方案1】:

    您可以使用 Combobox 的 SelectedIndexChanged 事件:

    private void nameComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
    {
              numberComboBox.SelectedIndex = descriptionComboBox.SelectedIndex = nameComboBox.SelectedIndex;
    }
    

    您必须事先关联事件处理程序:

    this.nameComboBox.SelectedIndexChanged += 
            new System.EventHandler(nameComboBox_SelectedIndexChanged);
    

    【讨论】:

    • 这个很好用,不需要关联事件处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多