我有一个列表框,其中添加了我选择的项目及其名称和价格。现在我想检查我选择的项目是否在列表框中,如果是,则替换它的价格并加倍。
我可以检查重复但无法更新价格。
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
if (CheckProductInListBox(details.Name))
{
// what to do ?
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString());
}
}
private bool CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return true;
}
}
return false;
}
答案 0 :(得分:0)
如果您使用您的功能查找并返回现有项目(如果找不到该项目,则在适当情况下为空字符串),然后您可以从那里向后工作。
假设项目的名称和添加的填充将始终相同,您可以简单地将其从现有项目中删除,并保留价格的字符串值。这可以很容易地解析为十进制值,然后可以将价格添加到现有总计中以生成新总计。
然后,使用这个新的总名称和之前相同的名称,您只需使用更新的字符串替换当前在该索引处的项目。
请注意,这不是最干净,最优雅的解决方案,因为这需要将整个方法重新设计为UI元素和数据的交互方式。
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
string foundItem = CheckProductInListBox(details.Name);
if (!String.IsNullOrEmpty(foundItem))
{
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
decimal currentPriceValue;
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
currentPriceValue += price;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
//Throw error
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString());
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}