我目前正在尝试使用内置的Array.BinarySearch
函数在列表框中搜索项目。这是针对项目的,因此我必须按要求的方式进行。
按现状,我正在一个文本框中输入信息,右键单击它会弹出一个ContextMenuStrip,然后我应该能够单击它,它将在列表视图中搜索匹配的数据并填充与该文本一起出现的其他文本框数据。
如果您在下面的图像中查找,这将有助于了解我在做什么。
这里是我的Binary.Search
的代码。
private void text_Opening(object sender, CancelEventArgs e)
{
Customer findCustomer = new Customer();
// Value to search for
string target = txtCustID.Text;
int pos = Array.BinarySearch(myCustomer, target);
if (string.Compare(myCustomer[], target, true) == 0)
{
MessageBox.Show("Customer found");
txtCustID.Text = findCustomer.gsCustID;
txtFullName.Text = findCustomer.gsFullname;
txtCity.Text = findCustomer.gsFullname;
txtEmail.Text = findCustomer.gsEmail;
}
else
MessageBox.Show("Customer not found");
}
我目前在myCustomer []的方括号之间需要一些内容,但我无法弄清楚]
不确定是否需要Array.BinarySearch
。为了使用它,您应该
Customer[] myCustomer
Customer
必须实现IComparable<Customer>
接口myCustomer
必须以升序顺序排序Customer
实例放入Array.BinarySearch
(不能仅将txtCustID.Text
放入][通常,如果您有Customer
的集合,例如
Customer[] myCustomer = ...
您可以尝试Linq
using System.Linq;
...
private void text_Opening(object sender, CancelEventArgs e) {
// Here, in the FirstOrDefault, we can put any condition
Customer findCustomer = myCustomer
.FirstOrDefault(customer => customer.CustId == txtCustID.Text);
if (findCustomer != null) {
// Customer found, (s)he is findCustomer
MessageBox.Show("Customer found");
// ...
}
else
MessageBox.Show("Customer not found");
}
编辑:如果您坚持使用Array.BinarySearch
(并且满足所有要求,请注意myCustomer
应该按[[升序由CustId
进行排序))然后
private void text_Opening(object sender, CancelEventArgs e) {
// We prepare artificial Customer to be found
Customer customerToFind = new Customer() {
CustId == txtCustID.Text,
};
int index = Array.BinarySearch(myCustomer, customerToFind);
if (index >= 0) {
Customer findCustomer = myCustomer[index];
MessageBox.Show("Customer found");
// ...
}
else
MessageBox.Show("Customer not found");
}