[英]Text box does not update after changing after selected item in ComboBox (ComboBox gets the list from a text file)
我在 WinForms 應用程序中遇到了 ComboBox 的問題。 組合框包含一個列表,其中包含從 TXT 文件中獲取的項目。 為了閱讀和更新列表,我將以下代碼添加到 Form_Load。
string[] lineOfContents = File.ReadAllLines(Application.StartupPath + @"Items.txt");
foreach(var line in lineOfContents)
{
string[] tokens = line.Split(',');
ComboBox.Items.Add(tokens[0]);
}
一切都很好,列表確實更新了。 但是,我也有一些文本框根據 ComboBox 中所選項目的字符串更改其文本。 例如,當 ComboBox 中的選中項為“示例”時,第一個文本框中的文本應由空變為“我是示例”。 但它沒有並且仍然為空:它的代碼是:
if(ComboBox.SelectedItem == "Example")
{
TextBox.Text = "I am an example!";
}
起初我認為這是一個轉換問題,所以我嘗試使用Convert.ToString(tokens[0]);
但它也沒有奏效。
關於我接下來應該嘗試解決此問題的任何建議?
您正在描述綁定行為,因此首先要檢查的是TextBox
是否正確綁定到ComboBox
。 像這樣的東西會起作用:
public MainForm()
{
InitializeComponent();
// Attach text box text to changes of combo box text
textBox1.DataBindings.Add(
nameof(textBox1.Text),
comboBox1,
nameof(comboBox1.Text)
);
}
但是我在您的代碼中注意到的另一件事是,在將令牌加載到組合框中后,您似乎沒有select組合框中的值。 這將文本框留空,如下所示:
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,",
};
因此,解決方案是確保在將令牌加載到ComboBox
后進行選擇,例如 [Load + Select] 按鈕的處理程序中所示:
private void buttonLoadPlusSelect_Click(object sender, EventArgs e)
{
loadMockFile();
var foundIndex = comboBox1.FindStringExact("Example");
comboBox1.SelectedIndex = foundIndex;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.