WPF datagrid错误:NullReferenceException,如何从datagrid中的每个单元格获取数据?

时间:2014-08-24 19:32:15

标签: c# wpf datagrid nullreferenceexception selecteditem

我有一个WPF程序,用于从数据网格中获取数据。 但是这个程序总是显示错误:NullReferenceException未被用户代码处理。对象引用未设置为对象的实例

有什么问题?以下是代码

 private string GetDatagrid(DataGrid grid)
    {
        var data = (ObservableCollection<ConfigViewModel>)grid.ItemsSource;
        StringBuilder dataStr = new StringBuilder();

        for (int i = 0; i < data.Count; i++)
        {

            for (int j = 0; j < grid.Columns.Count; j++)
            {
                TextBlock selectTextBlockInCell = grid.Columns[j].GetCellContent(data[i]) as TextBlock;

                string configVari= selectTextBlockInCell.Text; //This line comes the error!
                dataStr.Append(configVari);
                dataStr.Append("#");
            }
            dataStr.Remove(dataStr.Length - 1, 1);  
            dataStr.Append(@"\\");

        }

        return dataStr.ToString();
    }

1 个答案:

答案 0 :(得分:0)

看起来来自另一个SO帖子的this answer可能会成功。

获取数据网格的行。

public IEnumerable<Microsoft.Windows.Controls.DataGridRow> GetDataGridRows(Microsoft.Windows.Controls.DataGrid grid)
{
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as Microsoft.Windows.Controls.DataGridRow;
        if (null != row) yield return row;
    }
}

然后迭代它。

var rows= GetDataGridRows(nameofyordatagrid); 

foreach (DataGridRow r in rows)  
  {  
    DataRowView rv = (DataRowView)r.Item;
    foreach (DataGridColumn column in nameofyordatagrid.Columns)
    {
        if (column.GetCellContent(r) is TextBlock)
        {
            TextBlock cellContent = column.GetCellContent(r) as TextBlock;
            MessageBox.Show(cellContent.Text);
        }
  }