Search code examples
wpfdatagridrow

retrive values of datagrid Selected cell into Sql


i have got dategrid which populated from sql query

    HPEntities db = new HPEntities();
    var queryTable4 = db.Database.SqlQuery<Lbrctn>("select * from Lbrctn");
    var u = queryTable4.ToList();
    DG_Example.ItemsSource = u;

i want to get the values of those row of my dataGrid which has checked. and send to Stored Procedure so i try this code:

     for (int i = 0; i < DG_Example.Items.Count - 1; i++)
                {

                    mChkBox = DG_Example.Columns[0].GetCellContent(DG_Example.Items[i]) as CheckBox;

                    if (mChkBox.IsChecked == true)
                    {
                        
                        var DaSelect = DG_Example.Columns[1].GetCellContent(DG_Example.Items[i]) as TextBlock;
                        var MNameTBk = DG_Example.Columns[2].GetCellContent(DG_Example.Items[i]) as TextBlock;
                        var ChiCodeTBk = DG_Example.Columns[3].GetCellContent(DG_Example.Items[i]) as TextBlock;
                        var ChiNameTBk = DG_Example.Columns[4].GetCellContent(DG_Example.Items[i]) as TextBlock;

                        var IntenCodeTBk = DG_Example.Columns[6].GetCellContent(DG_Example.Items[i]) as TextBlock;
                        var PeDescTBk = DG_Example.Columns[7].GetCellContent(DG_Example.Items[i]) as TextBlock;
                        
                        db.sp_Ins_inten // using Stored Procedure
                            (
                            IntenCodeTBk.Text.Trim(),
                            MNameTBk.Text.Trim(),
                            Convert.ToInt32(chiCodeTBk.Text.Trim()),
                            ChiNameTBk.Text.Trim(),
                            PeDescTBk.Text.Trim(),
                            DaSelect.Text.Trim()
                            
                            );
                            
                        db.SaveChanges();

                    }

                }

is there a better way than GetCellContent to get values of datagrid row I could use? thanx in advance


Solution

  • all values can be found in a data item, displayed in a DataGridRow (except probably CheckBox, which is likely not bound):

    for (int i = 0; i < DG_Example.Items.Count - 1; i++)
    {
        mChkBox = DG_Example.Columns[0].GetCellContent(DG_Example.Items[i]) as CheckBox;
    
        if (mChkBox.IsChecked == true)
        {
            Lbrctn item = DG_Example.Items[i] as Lbrctn;
    
            db.sp_Ins_inten // using Stored Procedure
            (
                item.IntenCodeTBk,
                item.MNameTBk,
                item.Convert,
                item.ChiNameTBk,
                item.PeDescTBk,
                item.DaSelect
            );
    
            db.SaveChanges();
        }
    }