Search code examples
c#wpfdatagridcelledit

WPF Edit Datagrid cell value and then save, While editing I am lading into "application in break mode"


I am new to WPF. Please help me. There are 3 text box i.e. itemNO, qty and discount and there is one add button. Upon filling values in these text boxes then clicking the add button I want the item to be added in DataGrid. Till adding Item in DataGrid everything is fine. But while trying to edit item of the Datagrid cell I am landing into break mode. The code I wrote for that is

public class OrderItem
{
    public string ItemID { get; set; }
    public string ItemName { get; set; }
    public string Quantity { get; set; }
    public string Discount { get; set; }
    public int Price { get; set; }
}
private OrderItem GetOrder(string itemID, string qty, string discount)
{
    OrderItem orderItem = null;

    {
        DataView dv = BS.GetDataFromDb("where Id = " + itemID);
        if(dv != null && dv.Count > 0)
        {
            orderItem = new OrderItem();
            orderItem.ItemID = itemID;
            orderItem.ItemName = dv[0]["Name"].ToString();
            orderItem.Price = int.Parse(dv[0]["Price"].ToString());
            orderItem.Quantity = qty;
            orderItem.Discount = discount;
        }
        if (dv == null || dv.Count == 0)
            MessageBox.Show("Wrong item no: " + itemID, "Unavailable Item No", MessageBoxButton.OK, MessageBoxImage.Error);
    }
    return orderItem;
}
private void btnAddOrder_Click(object sender, RoutedEventArgs e)
{
   try {
       string discount = (txtDiscount.Text.Trim() == string.Empty ? "0" : txtDiscount.Text.Trim());
       int qty = int.Parse(txtQty.Text.Trim() == string.Empty ? "0" : txtQty.Text.Trim());
       int itemNo = int.Parse(txtItemNo.Text.Trim() == string.Empty ? "0" : txtItemNo.Text.Trim());
       if (qty <=0) { 
            MessageBox.Show("Please insert valid quantity", "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }
        if (itemNo <= 0) {
            MessageBox.Show("Please insert valid item number", "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }

        OrderItem o = GetOrder(txtItemNo.Text, txtQty.Text, discount);
        if(o != null)
        { 
            grdOrderList.Items.Add(new OrderItem { ItemName = o.ItemName, Price = o.Price, Quantity = o.Quantity, Discount = o.Discount });
            if (orderItems == null)
                orderItems = new List<OrderItem>();
            orderItems.Add(o);
            txtItemNo.Text = txtQty.Text = txtDiscount.Text = string.Empty;
        }
    }
    catch (Exception ex) {
        MessageBox.Show("Error 69: "+ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

Untill adding itemId, quantity and discount by clicking on Add item button everything is working fine. In DataGrid to edit the cell value of Quantity column I made that column as Editable (i.e. ReadOnly = "False"). But while trying to edit the cell value of Quantity I am landing into break mode (i.e. The application is in break mode). I will be very thankful for the help. Below is the XAML code

<StackPanel Name="YourOrder">
      <StackPanel>
          <TextBox Name="txtItemNo" />
          <TextBox Name="txtQty"  />
          <TextBox Name="txtDiscount"  />                           
          <Button Name="btnAddOrder" Click="btnAddOrder_Click" Content="Add to order" ToolTip="Adds item to order" />
      </StackPanel>
      <DataGrid Name="grdOrderList">
          <DataGrid.Columns>
               <DataGridTextColumn Header="Item Name" Binding="{Binding ItemName}" MinWidth="100" IsReadOnly="True" />
               <DataGridTextColumn x:Name="hdrPrice" Header="Price" Binding="{Binding Price}" MinWidth="20" IsReadOnly="True"  CellStyle="{StaticResource DgcRight}" />
               <DataGridTextColumn x:Name="hdrQty" Header="Qty" IsReadOnly="False" MinWidth="20" Binding="{Binding Quantity}" />
               <DataGridTextColumn x:Name="hdrDiscount"  Header="Discount" Binding="{Binding Discount}" MinWidth="50" CellStyle="{StaticResource DgcRight}" />
          </DataGrid.Columns>
     </DataGrid>
</StackPanel>

Solution

  • In your .xaml, try adding the following attributes:

    DataGrid Name="grdOrderList" CanUserAddRows="True"
    

    I would also suggest that instead of trying to update the list items directly in the view, to using a binding to an ObservableCollection in the ViewModel that is the DataSource for the view. This way, you can just update the collection in code, and your list can be updated from actions that are not directly in the code-behind (.xaml.cs file) that is linked to the view. To do that, your DataGrid definition would also add:

    DataGrid Name="gdrOrderList" CanUserAddRows="True" ItemsSource={"Binding ListInViewModel"}