我有一个列表框,我的选定产品就像这样存储......
'产品名称'.padright(30)'价格''数量'
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
但是当我读取产品的价格时,它会选择价格和数量
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
我只想要currentPriceString
中的价格和quantityString
这是此方法的完整代码
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;
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
int quantiy;
MessageBox.Show(currentPriceString);
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
quantiy = Convert.ToInt16(quantityString);
currentPriceValue += price;
quantiy++;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString() + quantiy.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
MessageBox.Show("Error");
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}
答案 0 :(得分:0)
在替换(foundItem.Replace(details.Name.PadRight(33), "");
)时,您只是从字符串中删除名称部分,因此价格和数量肯定会存在。
你应该可以试试这段代码,
// suppose your found text is like this,
//foundItem = "AMIT".PadRight(30) + "200" + " " + "1";
您可以单独获得价格和数量,如下所示:
string currentPriceQuantityString = foundItem.Replace(details.Name.PadRight(30), "");
//currentPriceQuantityString => "200 1"
string[] strArray = currentPriceQuantityString.Split();
string currentPriceString = strArray[0]; //currentPriceString => "200"
string quantityString = strArray[1]; //quantityString => "1"
旁注:
我想你的话:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
..应该是:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + "1" );