简体   繁体   中英

Text box does not update after changing after selected item in ComboBox (ComboBox gets the list from a text file)

I am confronting with an issue with the ComboBox in a WinForms app. The combo box contains a list with items that are grabbed from a TXT file. To read and update the list I added the following code to Form_Load.

string[] lineOfContents = File.ReadAllLines(Application.StartupPath + @"Items.txt");
        foreach(var line in lineOfContents)
        {
            string[] tokens = line.Split(',');
            ComboBox.Items.Add(tokens[0]);
        }

All nice and good, the list does update. However, I also have some TextBoxes that are changing their text based on the string of the selected item in the ComboBox. For example, when the selected item in the ComboBox is "Example", the text in the first text box should change from empty to "I am an example,". but it doesn't and remains empty: The code for it is:

if(ComboBox.SelectedItem == "Example")
        {
            TextBox.Text = "I am an example!";
         }

At first I though it's a conversion issue so I tried to use Convert.ToString(tokens[0]); but it did not work as well.

Any suggestions on what I should try next to fix this issue?

You are describing bound behavior so the first thing to check is whether the TextBox is properly bound to the ComboBox . Something like this would work:

public MainForm()
{
    InitializeComponent();

    // Attach text box text to changes of combo box text
    textBox1.DataBindings.Add(
        nameof(textBox1.Text),
        comboBox1,
        nameof(comboBox1.Text)
    );
}

But the other thing I notice in your code is that you don't seem to select a value in the combo box after loading the tokens into it. This leaves the text box blank as demonstrated here:

private void buttonLoad_Click(object sender, EventArgs e)
{
    loadMockFile();
}

private void loadMockFile()
{
    string[] lineOfContents = MockFile;
    foreach (var line in lineOfContents)
    {
        var token = 
            line.Split(',')
            .Select(_ => _.Trim())
            .Distinct()
            .First();
        if (!comboBox1.Items.Contains(token))
        {
            comboBox1.Items.Add(token);
        }
    }
}

string[] MockFile = new string []
{
    "Example, A, B,",
    "Other, C, D,",
};

需要选择


So the solution is to make sure that you make a selection after the tokens are loaded into the ComboBox , for example as shown in the handler for the [Load + Select] button:

private void buttonLoadPlusSelect_Click(object sender, EventArgs e)
{
    loadMockFile();
    var foundIndex = comboBox1.FindStringExact("Example");
    comboBox1.SelectedIndex = foundIndex;
}

加载后选择

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM