简体   繁体   中英

How to Get a Cell Content of DataGrid which is not Selected in WPF?

在此处输入图片说明 1. how to Calculate a Price Cell. 2. their is no record is selected. 3. At end it show sum of price cell.

private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        try
        {
            string s = dataGrid1.Columns[2].GetCellContent(e.Row).ToString();
           //give me a Null Reference Error

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

Try this :

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
   sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}

LoadingRow event gives you the current DataGridRow , so you need to access the corresponding Item to that DataGridRow .

So, Change this

   string s = dataGrid1.Columns[2].GetCellContent(e.Row).ToString();

to something similar to :

   MyItem item = Dgrd.ItemContainerGenerator.ItemFromContainer(e.Row) as MyItem;
   if (item != null)
   {
       System.Diagnostics.Debug.WriteLine(item.Name);
   }

or,

    MyItem i =  e.Row.DataContext as MyItem;        
    if (item != null)
    {
        System.Diagnostics.Debug.WriteLine(item.Sku);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM