我处于某种情况,我想知道它是否有可能。
我想根据TextBox值更改ListBox控件的Items。
表示当我更改文本框值时,ListBox的列表项异步更改(不按按钮或其他内容)。
有可能吗?如果有可能请指导我一些参考,教程或其他东西。
答案 0 :(得分:1)
不完全得到你需要的东西,但我希望下面的案例可以帮到你;
案例1:如果您的列表框中包含多个项目,并且您希望选择与文本框中的文本匹配的项目。如果是这种情况,则下面的代码应该完成这项工作;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.TextLength >= 1)
{
int index = listBox1.FindString(textBox1.Text);//Search any items that match Textbox's text.
listBox1.SelectedIndex = index;//Highlight the match
}
else
{
listBox1.SelectedIndex = 0;
}
}
将上面的代码添加到文本框的TextChangedEvent中,并确保使用您拥有的代码重命名代码中的控件。如果不是这种情况,请参阅下面的内容;
案例2:你有一个文本框,你想将文本框的文本添加到列表框。我想告诉你更多的事情,下面的代码假设当你按,它的文本(如果有的话)应该被添加到列表框中。在文本框的KeyDownEvent中添加下面的代码,并确保重命名控件。如果是这样的代码下面会帮助你;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string item = textBox1.Text;
if (textBox1.Text.Length >= 1)
{
if (e.KeyCode == Keys.Enter)//If Enter key is pressed while textbox is focused.
{
listBox1.Items.Add(item);
}
}
}
希望这会对你有所帮助。
答案 1 :(得分:0)
我希望以下代码能为您提供帮助:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if(TextBox1.Text == "One")
listBox1.Items.Add("One");
if(TextBox1.Text == "two")
listBox1.Items.Add("two");
}
答案 2 :(得分:0)
您不必执行该异步操作。只需使用TextBox.TextChanged-Event。