【问题标题】:Error when get data from the datagrid从数据网格获取数据时出错
【发布时间】:2014-08-22 10:34:29
【问题描述】:

下面的代码是从datagrid中获取第一列数据,做一些字符串操作,但是报错,

已处理 NullReferenceException 对象引用未设置为对象的实例。

有什么问题? 如果我想获取第一列的每一个数据,该怎么做?

private string getit(DataGrid grid)
{
    StringBuilder stringStr = new StringBuilder();

    for (int i = 0; i < grid.Items.Count; i++)
    {
        TextBlock selectTextBlockInCell = grid.Columns[0].GetCellContent(i) as TextBlock;
        string inputName = selectTextBlockInCell.Text;

        stringStr.Append(@"\pic () at (-0.5,");
        stringStr.Append(3 - i);
        stringStr.Append(inputName);
        stringStr.Append(@"}");
    }

    return stringStr.ToString();
}

【问题讨论】:

  • 这不是您使用 WPF 数据网格的方式。不要遵循windows窗体应用方式
  • 不知道WPF中的方式是什么,是怎么工作的?
  • 请参阅这篇 [post][1] 关于获取 WPF DataGrid 的单元格内容。 [1]:stackoverflow.com/questions/13204536/…

标签: c# wpf datagrid wpfdatagrid


【解决方案1】:

阅读有关 DataGridColumn.GetCellContent() 的 MSDN 文档,尤其是有关应将什么参数传递给该方法的信息。然后你就会知道它接收的不是行索引,而是“由包含预期单元格的行表示的数据项”

尝试对DataGrid的底层数据源进行操作,例如:

//cast to correct type
var data = (ObservableCollection<MyClass>)grid.ItemsSource;
StringBuilder stringStr = new StringBuilder();
//loop through your data instead of DataGrid it self
for (int i = 0; i < data.Count; i++)
{
    //get the value from correct property of your class model
    string inputName = data[i].MyProperty;
    //or if you really have to get it from cell content :
    //TextBlock selectTextBlockInCell = grid.Columns[0].GetCellContent(data[i]) as TextBlock;
    //string inputName = selectTextBlockInCell.Text;

    stringStr.Append(@"\pic () at (-0.5,");
    stringStr.Append(3 - i);
    stringStr.Append(inputName);
    stringStr.Append(@"}");
}
return stringStr.ToString();

WPF 旨在与数据绑定一起使用,以便我们可以清楚地分离 UI 和数据(阅读有关 MVVM 模式的信息)。应用程序逻辑不应该关心 UI,因此最好在 UI 控件上进行操作。而是对模型/视图模型进行逻辑操作,并让数据绑定将模型/视图模型传递给 UI/视图。

*) 从data.ItemsSource 获取数据只是一种简化的方式,从 OP 目前拥有的内容开始。最终的方法是拥有一个存储数据的属性并将ItemsSource 绑定到该属性。

【讨论】:

  • 谢谢!但是如果我真的需要从datagrid单元格中获取数据,而不是通过数据绑定源,该怎么做呢?
  • 为什么你不能从grid.ItemsSource得到它?
  • 因为不知道源码在哪里,所以我们的代码没有遵循绑定规则...
  • 您不必知道来源在哪里。如果您的意思是您不知道 grid.ItemsSource 中存储的对象的正确类型,您可以简单地调试并使用 Visual Studio 的“监视”窗口查看实际类型。..
猜你喜欢
  • 2018-01-11
  • 2020-04-26
  • 2019-07-10
  • 1970-01-01
  • 2018-12-20
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多