0
Answer

WPF – datagrid data binding at runtime

Ali Shahbaz

Ali Shahbaz

11y
5k
1
I have a datagrid view and have set its property "CanUserAddRows" to "True", I have assigned a null list to its ItemsSource, it show me first blank row. Exactly I want. Actually my scenario is that, user can add multiple rows, on very first column, when a user add "PartyCode" I need to display "PartyName" based on "PartyCode" I can get "PartyCode" from code behind, but problem is that I can't bind "PartyName" to datagrid If I use dg.Items.Add(obj), then I get exception " 'EditItem' is not allowed for this view."
Here is a snap shot for understanding enter image description here
I call a function "CellEditEnding" to achieve this functionality, that is

private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            TextBox t = e.EditingElement as TextBox;  // Assumes columns are all TextBoxes
            DataGridColumn dgc = e.Column;
            DataGridRow dgr = e.Row;
            Party p = new PartiesDAL().GetByPartyCode(Numerics.GetInt(t.Text));
            if (dgc.DisplayIndex == 0)
            {
                if (p != null)
                {
                    CashBookDetail cb = new CashBookDetail();
                    cb.PartyCode = p.PartyID;
                    cb.PartyName = p.PartyName;
                    cb.Remarks = "";
                    cb.Amount = 0;
                    list.Add(cb);
                    LoadGrid(); // list is public, add an object to list and call again LoadGrid() to load records
                }
                else
                {
                    Xceed.Wpf.Toolkit.MessageBox.Show("Party does not exist", "", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }


I also want, when user on third column at "Amount", and press enter, it should add new row and focus should move on 2nd row and 1st column
This is screen shot, may it help u to understand, exactly I want this enter image description here