SaraniO
SaraniO

Reputation: 607

How to set a datagridview values to it's datasource

I want to pass datasource of a datagridview to another Form,

this is how i do that:

private void RationSummary_Click(object sender, EventArgs e)
{
    RationReportFrm RRFrm = new 
    RationReportFrm(HomeDetailsdgv.DataSource, RationFormulationdgv;

    RRFrm.ShowDialog();
}

and

public RationReportFrm(object RationTotalds, object HomeTotalds)
{
    InitializeComponent();


    AnimalPerformancedgv.DataSource = RationTotalds;
    ProteinValuedgv.DataSource = HomeTotalds;
 }

now the question is:

datasource of one of these datagridviews has set by a datatable and it passes to RationReportFrm without any problem, but one of them dosen't have any datasource and it's cells filled programmatically, How should I set it's cells values to it datasource in order to pass it to another form?

Upvotes: 0

Views: 751

Answers (1)

SaraniO
SaraniO

Reputation: 607

I think the beset way is to make a method to convert datagridview to a datatable

private DataTable GetDTFromDGV(DataGridView dgv)
{
    var dt = new DataTable();

    foreach (DataGridViewColumn column in dgv.Columns)
    {
        if (column.Visible)
        {
            dt.Columns.Add();
            if (column.Name != "")
            {
                dt.Columns[column.Index].ColumnName = column.Name;
            }
        }
    }

    object[] CellValue = new object[dgv.Columns.Count];

    foreach (DataGridViewRow row in dgv.Rows)
    {
        for (int i = 0; i < row.Cells.Count; i++)
        {
            CellValue[i] = row.Cells[i].Value;
        }
        dt.Rows.Add(CellValue);
    }

    return dt;
}

Upvotes: 1

Related Questions