[英]How to populate a textbox with an array index from the combobox selected index of a different array
我已经从一个文本文件创建了两个字符串数组,并用array1填充了一个组合框。 我想了解的是,如何获得一个文本框来显示与组合框(array1)的选定索引匹配的array2索引?
我认为这样可能有效:
if(phoneComboBox.Text == cPhone[index])
{
nameTextBox.Text = cName[index]; //show equal index item to cPhone/phoneComboBox
}
但这似乎不起作用。 我也尝试过foreach循环,也许我只是做错了。 我已经读取了window_loaded事件中的文本文件和数组,并且不知道这是否是问题。 我已经看到SelectedIndexChanged事件在类似的问题中提到很多,但是我没有使用该事件,只是SelectionChanged。
有人可以为此指出我正确的方向吗? 我知道数组可能不是这里的最佳用法,但是它们是我使用过的,所以请帮助我正确理解它。
这就是我阅读数组的方式:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
//read file on start
int counter = 0;
string line;
StreamReader custSR = new StreamReader(cFileName);
line = custSR.ReadLine();
while (line != null)
{
Array.Resize(ref cPhone, cPhone.Length + 1);
cPhone[cPhone.Length - 1] = line;
counter++;
line = custSR.ReadLine();
Array.Resize(ref cName, cName.Length + 1);
cName[cName.Length - 1] = line;
counter++;
line = custSR.ReadLine();
phoneComboBox.Items.Add(cPhone[cPhone.Length - 1]);
}
custSR.Close();
/*string changeAll = string.Join(Environment.NewLine, cPhone);
string allOthers = string.Join(Environment.NewLine, cName);
MessageBox.Show(changeAll + allOthers);*/
//focus when program starts
phoneComboBox.Focus();
}
在中,如果要比较文本字符串,则应使用函数“ .Equals”代替
“ ==”
if(phoneComboBox.Text.Equals(cPhone[index]))
{
nameTextBox.Text = cName[phoneComboBox.SelectedIndex];
}
您无需检查条件,只需获取选定的索引:
nameTextBox.Text = cName[phoneComboBox.SelectedIndex];
在WPF
您具有SelectionChanged
。
SelectedIndexChanged
用于winform
。
最佳实践:
但我建议您使用Tag属性实现此目的的更好方法。 您不必为此更改很多代码。
//Create "ComboBoxItem" instead of "array"
while (line != null)
{
//initialize
ComboBoxItem cmItem = new ComboBoxItem();
//set Phone as Display Text
cmItem.Content = line; //it is the Display Text
//get Name
line = custSR.ReadLine();
//set Tag property
cmItem.Tag = line; //it is the attached data to the object
//add to "Items"
phoneComboBox.Items.Add(ComboBoxItem);
}
现在,在SelectionChanged
事件中获取所选项目非常简单:
void phoneComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
nameTextBox.Content = (e.AddedItems[0] as ComboBoxItem).Tag;
}
您不再需要处理这些数组。
感谢您提供其他答案,这就是我想出的答案。 修复了我得到的indexOutOfRange异常。
private void phoneComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (phoneComboBox.SelectedIndex != -1)
{
nameTextBox.Text = cName[phoneComboBox.SelectedIndex];
}
else
{
nameTextBox.Text = string.Empty;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.