pass datagridview from one form to another c#

后端 未结 1 1830
盖世英雄少女心
盖世英雄少女心 2021-01-16 11:11

i want to pass my datagridview from form1 to form2.I\'ve tried with constructor but without result, datagridview in second form is empty. Could someone help me here, i\'m st

相关标签:
1条回答
  • 2021-01-16 11:38

    If you want to pass DataGridView from one form to another you might have to pass DataGridView.DataSource of DataGridView from one Form to other. Something like that

    new SecondForm(dataGridView.DataSource)
    

    and your SecondForm will accepts passed DataSource and pass that to DataGridView of that form

    class SecondForm
    {
        public SecondForm(object dataSource)
        {
            InitializeComponents();
    
            dataGridView.DataSource = dataSource;
        }
    }
    

    If you want to pass copy of DataSource you can create a new DataTable from existing data inside DataGridView of FirstForm

    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;
    }
    

    and update first call to this

    new SecondForm(GetDataTableFromDGV(dataGridView))
    
    0 讨论(0)
提交回复
热议问题