首先,在对数据进行任何操作之前,您总是需要验证用户输入。
int barcode = Convert.ToInt32(txt_barcode.Text);
如果用户在您的
TextBox
你可以这样做:
int barcode;
if(!Int.TryParse(txt_barcode.Text, out barcode))
{
MessageBox.Show("Please enter a valid barcode!");
return;
}
请记住,条形码值并不总是数字的,因此现实世界中的场景很可能会要求字符串值。
我认为没有充分的理由保留
Product
和
Barcode
值分离。创建一个简单的类用作您的模型,如下所示:
public class Product
{
string barcode;
public string Barcode
{
get => barcode;
set => barcode = value;
}
string product_name;
public string ProductName
{
get => product_name;
set => product_name = value;
}
}
然后当你填写
Collection
你可以这样做:
// This is the collection you will be storing your products in
List<Product> Products = new List<Product>();
private void btn_add_Click(object sender, EventArgs e)
{
string barcode = txt_barcode.Text;
string product = txt_product.Text;
Product myProduct = new Product()
{
Barcode = barcode,
ProductName = product
};
Products.Add(Product); // MyCollection is of List<Product> type
}
然后你可以通过以下产品列表来搜索整个内容:
private Product SearchForProduct()
{
foreach (Product p in Products)
{
// This will return the first product that matches either of the cases
// Play around with you search logic
if (p.Barcode == "YourSearchTerm" || p.ProductName == "YourSearchTerm")
{
return p; // Returns the product that matches the search terms
}
}
return null; // Returns null if no product matching the search term is found
}
然后,您可以这样调用该方法:
Product search_result = SearchForProduct(search_textbox.Text);
if(search_result == null)
{
MessageBox.Show("No Product matching the search terms was found!");
return;
}
else
{
// Do something with the found product
}