C# 从列表框中提取特定部分并对其进行进一步操作

C# Extract a specific part from list box and perform further operation on it

Order item 会将数据从 list box items 移动到 list box order,并且每个订购商品的数量在文本框中提供。如果汉堡的 qty 是 2 而不是 list box order 它被保存为。

Burger#2#100

我可以转移一个选定的项目但是如何提取那个特定的数字然后乘以它...困惑 这里没有任何硬编码,基本上我必须为按钮编写代码,它将数量乘以列表框中的数量我正在尝试以下操作:

 private void btnorder_Click(object sender, EventArgs e)
        {
            //int index = listboxitem.SelectedIndex;

            string itemadd = listboxitem.SelectedItem.ToString().Replace(" ", "#");
            listboxorder.Items.Add(itemadd);

            string item = listboxitem.SelectedItem.ToString();
          //  string[] text = listboxitem.Items.Replace(" ","#");
           
        }

第 1 步:创建具有以下属性的 MenuItem class 或结构:

 String Name;  //Pizza  
 int Price; // 1200  
 public override String ToString()  
 { return Name + " " + "Rs " + Price; }

根据您的操作方式,您可能需要添加 ID 字段。

构建这些项目并将其添加到列表框中,

参见:Adding objects to a listbox (Whosebug)

第 2 步:创建 OrderItem class,

 MenuItem item;
 int quantity;
 public OrderItem(MenuItem menuitem, int quantity) { //errorcheck and populate fields}
 public override String ToString()
 {  return item.Name + "#" + quantity + "#" + item.Price * quantity;}

第 3 步:创建订单点击处理程序

private void btnorder_Click(object sender, EventArgs e)  
{  
     MenuItem itemadd = (MenuItem)listboxitem.SelectedItem;  
     int quant = Convert.ToInt32(textboxQuantity.Text); // needs validation and exception handling  
     OrderItem oitem = new OrderItem(itemAdd, quant);      
     listboxorder.Items.Add(itemadd);  
}

这是对问题的初步了解,但由于我不知道数据来自何处,所以我将其保持得非常基本。

您可能希望将数量文本框更改为下拉列表或其他将输入限制为整数的控件。

您需要 String.Split() on your input to get the values separated out by spaces into a string array. Afterwards, you'll need to convert both the cost and quantity to integers with int.TryParse() so you can do math with them. Then you'll replace the cost in the string array with the computed total and put the string array back together with String.Join() 使用“#”作为分隔符。

可能看起来像:

private void btnorder_Click(object sender, EventArgs e)
{
    if (listboxitem.SelectedIndex == -1)
        return; // nothing was selected

    string[] values = listboxitem.SelectedItem.ToString().Split(' ');
    if (values.Length == 3)
    {
        int itemCost, quantity;
        if (int.TryParse(values[2], out itemCost) && int.TryParse(textboxquantity.Text, out quantity))
        {
            if (itemCost >=0 && quantity > 0)
            {
                int totalCost = itemCost * quantity;
                values[2] = totalCost.ToString();
                string order = String.Join("#", values);
                listboxorder.Items.Add(order);
                return;
            }                    
        }
    }

    // something went wrong
    // either the item was formatted incorrectly
    // or the item cost or quantity was not a valid integer
    MessageBox.Show("Error Adding Item");
}