0

在我的应用程序中,需要将我的数据网格转换为数据表,我通过引用传递数据表和数据网格。这是我的功能。

public static void ConvertGridToTable(ref Datatable dt, ref Gridview grd)
4

2 回答 2

2
 public static void ConvertGridToTable(ref DataTable dt, ref GridView grd)
    {
        try
        {
            if (grd.Rows.Count <= 0) return;

            for (int i = 0; i <= grd.Columns.Count - 1; i++)
            {
                if (grd.Columns[i].GetType().Name.Equals("BoundField"))
                {
                    BoundField bf = (BoundField)grd.Columns[i];
                    dt.Columns.Add(bf.DataField.ToString());
                }
            }

            for (int i = 0; i <= grd.Rows.Count - 1; i++)
            {
                dt.Rows.Add();
                for (int j = 0; j <= grd.Columns.Count - 1; j++)
                {
                    if (grd.Columns[j].GetType().Name.Equals("BoundField"))
                    {
                        BoundField bf = (BoundField)grd.Columns[j];
                        for (int k = 0; k <= dt.Columns.Count - 1; k++)
                        {
                            if (dt.Columns[k].ColumnName.Trim().Equals(bf.DataField.ToString()))
                            {
                                string value = grd.Rows[i].Cells[j].Text.Trim().Contains("&nbsp;") ? grd.Rows[i].Cells[j].Text.Trim().Replace("&nbsp;", string.Empty) : grd.Rows[i].Cells[j].Text.Trim();
                                dt.Rows[i][bf.DataField.ToString()] = value;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
于 2013-09-20T06:15:32.083 回答
0

你也可以这样做: -

var dataTable = new DataTable();

Array.ForEach(
dataGridView1.Columns.Cast<DataGridViewColumn>().ToArray(), 
arg => dataTable.Columns.Add(arg.HeaderText, arg.ValueType));
Array.ForEach(
dataGridView1.Rows.Cast<DataGridViewRow>().ToArray(), 
arg => dataTable.Rows.Add(arg.Cells.Cast<DataGridViewCell>().Select(cell => cell.Value)));

return dataTable;
于 2013-09-20T06:20:58.260 回答