我是xaml和c#的新手,如果ProductID已经存在,如何阻止我的按钮点击事件向Listview添加新行
private void btnAddToOrder_Click(object sender, RoutedEventArgs e)
{
//addtoorders
if (listStocks.SelectedIndex >= 0)
{
DataRowView row = (DataRowView)listStocks.SelectedItems[0];
List<Orders> orders = new List<Orders>();
orders.Add(new Orders()
{
ProductID = row["productID"].ToString(),
ProductName = row["productName"].ToString(),
Price = Convert.ToDouble(row["sellingPrice"]),
Quantity = Convert.ToInt32(row["quantity"])
});
listOrders.Items.Add(orders);
}
}
答案 0 :(得分:1)
首先为什么要创建Orders的新对象?
您可以使用需要
的LINQ using System.Linq;
然后使用
var found = ordersobject.FirstOrDefault(x => x.Contains(row["productID"].ToString())); //Replace ordersobject with the Orders object that you have created
最后,如果var found返回null,则添加产品,即
private void btnAddToOrder_Click(object sender, RoutedEventArgs e)
{
//addtoorders
if (listStocks.SelectedIndex >= 0)
{
DataRowView row = (DataRowView)listStocks.SelectedItems[0];
var found = ordersobject.FirstOrDefault(x=>x.Contains(row["productID"].ToString()));
if(found == null)
{
//According to my knowledge a new object i.e.,
//List<Orders> orders = new List<Orders>(); doesn't have to be defined below
//provided that you have defined an object of class Orders before,
//unless you want to create various objects of Orders.
//Which will cause a lot of trouble in future.
List<Orders> orders = new List<Orders>();
orders.Add(new Orders()
{
ProductID = row["productID"].ToString(),
ProductName = row["productName"].ToString(),
Price = Convert.ToDouble(row["sellingPrice"]),
Quantity = Convert.ToInt32(row["quantity"])
});
listOrders.Items.Add(orders);
}
}
}
}
答案 1 :(得分:1)
我认为本准则可以帮助您:
private void btnAddToOrder_Click(object sender, RoutedEventArgs e)
{
//addtoorders
if (listStocks.SelectedIndex >= 0)
{
DataRowView row = (DataRowView)listStocks.SelectedItems[0];
Orders o=(Orders)row;
List<Orders> orderlist=( List<Orders>)listOrders.ItemsSource;
if(orderlist.Find(x=>x.PRoductID==c1.PRoductID)!=null)
{
MessageBox.Show("This Product already exists!");
}
else
{
listOrders.Items.Add(orders);
}
}
}
答案 2 :(得分:1)
private void btnAddToOrder_Click(object sender, RoutedEventArgs e)
{
//addtoorders
if (listStocks.SelectedIndex >= 0)
{
DataRowView row = (DataRowView)listStocks.SelectedItems[0];
Orders newOrder = new Orders()
{
ProductID = row["productID"].ToString(),
ProductName = row["productName"].ToString(),
Price = Convert.ToDouble(row["sellingPrice"]),
Quantity = Convert.ToInt32(row["quantity"])
};
List<Orders> orders = new List<Orders>();
//
bool found = false;
foreach(Orders order in orders)
{
if (order.Equals(newOrder))
{
//if Found Order Equal NewOrder
found = true;
break;
}
}
if(found == true)
{
Console.WriteLine("We are Found Order = NewOrder");
return; //Exit From Method
}
//If Found == false
orders.Add(newOrder);
listOrders.Items.Add(orders);
}
}