【问题标题】:DataGridView without DataSource to XML string没有 DataSource 的 DataGridView 到 XML 字符串
【发布时间】:2018-10-28 16:04:33
【问题描述】:

我在一个表单上有一些 DataGridViews,并想从中获取一个 XML 字符串。 但由于某种原因,它在返回时给出了“Exception throw: 'System.NullReferenceException'”。 当我查看 foreach 行内部时,它包含我输入的数据。 这里有什么问题?

    public string DataGridViewToXML(DataGridView DGV)
    {
        DataTable DT = new DataTable();
        foreach (DataGridViewColumn col in DGV.Columns) { DT.Columns.Add(col.Name); }
        foreach (DataGridViewRow row in DGV.Rows)
        {
            DataRow dRow = DT.NewRow();
            foreach (DataGridViewCell cell in row.Cells) { dRow[cell.ColumnIndex] = cell.Value; }
            DT.Rows.Add(dRow);
        }
        return DT.DataSet.GetXml();
    }

【问题讨论】:

  • 您的DataTable DT没有DataSet。
  • 好清楚,所以我填充数据表的方式不会创建数据集。网上搜了下,还是没有办法只保存用户放在DataGridView中的数据,难不成?

标签: c# .net windows winforms visual-studio


【解决方案1】:

你还没有告诉它在哪一行,但是当我得到它时,你将所有数据从DGV复制到DT,这样你就可以解析DataSet.GetXml();

如果是这样,你为什么不这样做:

public string DataGridViewToXML(DataGridView DGV)
{
    return (DGV.DataSource as DataTable).DataSet.GetXml();
}

我知道它不能解决你的 null 错误,但是当你有更简单的方法来执行命令时,你为什么要解决它。其他方式告诉我什么线路错误下降,我会尝试解释它发生的原因。

【讨论】:

  • 在这种情况下我没有 .dataSource
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多