我如何从datagridview写入文件

时间:2015-02-24 14:40:17

标签: c# datagridview xmlwriter

我试图从datagridview写入,目的是保存对xml文件的输入,但是没有正确地获取它。我的代码:

XDocument doc = XDocument.Load(outputFilePath);
doc.Save(outputFilePath);
oDataSet = new DataSet();

foreach (DataGridViewRow _rows in Gridview_Output.Rows)
{
    DataRow oDatarow = oDataTable.NewRow();
    for (int i = 0; i < Gridview_Output.ColumnCount; i++)
    {
        oDataTable.Rows.Add(oDatarow.ItemArray);
    }
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(outputFilePath);
doc.Save(outputFilePath);

我想写这个空标签:

<data name="Exit_Button" xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp][Comment][/Comment]</comment>
</data>

1 个答案:

答案 0 :(得分:1)

嗯尝试这个从gridview创建一个数据表:

private DataTable GetDataTableFromDGV(DataGridView dgv) {

    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }
    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
            dt.Rows.Add(cellValues);
    }
    return dt;
}

然后你可以这样做:

DataTable dT = GetDataTableFromDGV(DataGridView1);
DataSet dS = new DataSet();
dS.Tables.Add(dT);
dS.WriteXml(File.OpenWrite("xml.xml"));