Share via

How to transfer selected row(s) in dgv1 of Form1 to dgv2 of Form2 and come to select others then save under the previously added in dataGridView2

Primer 41 Reputation points
Sep 9, 2022, 7:32 AM

Transfer selected rows in dgv1 of Form1 to dgv2 of Form2 many times

Sep 9 2022 6:57 AM

Hello everyone on this platform;

I really want to transfer selected rows from dataGridView1 of Form1 to dataGridView2 of Form2. I'm able to select rows and transfer them for the first time but the case is that I'm failing to select other rows in dataGridView1 of Form1 and add them under the previously added rows in dataGridView2 of Form2.

I tried the following codes and are executed after clicking a button to transfer selectd rows.:

private void btn_PassDta_Click(object sender, EventArgs e)  
        {  
            List<CommonValue> CV = new List<CommonValue>();  
            foreach (DataGridViewRow item in dataGridView1.Rows)  
            {  
                if (Convert.ToBoolean(item.Cells[0].Value))  
                {  
                    CV.Add(new CommonValue  
                    {  
                        Colum1 = item.Cells[1].Value.ToString(),  
                        Colum2 = item.Cells[2].Value.ToString(),  
                        Column3 = item.Cells[3].Value.ToString()  
  
                    });  
                }  
            }  
  
            Result_Form frm = new Result_Form();  
            frm.Values = CV;  
            frm.Show();  
        }  

// The CommonValue in the above codes is a class created for set; and get

239329-imag.png

I need to come and reselect other row in dataGridView1 of Form1, click the button then find the selected row(s) under the previously transferred row (in Blue color) in dataGridView2 of Form2 to have many as selected from dataGridView1.

I will appreciate everyone's help.

Regards!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,307 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,801 Reputation points Microsoft Vendor
    Sep 9, 2022, 9:20 AM

    @Primer , Welcome to Microsoft Q&A, you could set a bool variable to check if the another form is opened. Then you could use datagirdview.Datasource to add the data in the second form.

    Here is a code example you could refer to.

    Form1:

     public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            private void Form1_Load(object sender, EventArgs e)  
            {  
                DataTable dataTable = new DataTable();  
                dataTable.Columns.Add("select",typeof(bool));  
                dataTable.Columns.Add("Col1",typeof(string));  
                dataTable.Columns.Add("Col2", typeof(string));  
                dataTable.Columns.Add("Col3", typeof(string));  
                dataTable.Columns.Add("Col4", typeof(string));  
                dataTable.Rows.Add(false, "test1", "test2", "test3", "test4");  
                dataTable.Rows.Add(false, "test3", "test4", "test5", "test6");  
                dataTable.Rows.Add(false, "test5", "test6", "test7", "test8");  
                dataTable.Rows.Add(false, "test7", "test8", "test9", "test10");  
                dataGridView1.AllowUserToAddRows = false;  
                dataGridView1.DataSource = dataTable;  
            }  
             
            bool t = false;  
            private void button1_Click(object sender, EventArgs e)  
            {  
                List<CommonValue> CV = new List<CommonValue>();  
                foreach (DataGridViewRow item in dataGridView1.Rows)  
                {  
                    if (Convert.ToBoolean(item.Cells[0].Value))  
                    {  
                        CV.Add(new CommonValue  
                        {  
                            Colum1 = item.Cells[1].Value.ToString(),  
                            Colum2 = item.Cells[2].Value.ToString(),  
                            Column3 = item.Cells[3].Value.ToString()  
      
                        });  
                    }  
                }  
                if(t==false)  
                {  
                    Form2 form2 = new Form2();  
                    form2.Show();  
                    t = true;  
                    form2.gridView.DataSource=CV;  
                }  
                else  
                {  
                    Form2 form2 = (Form2)Application.OpenForms["Form2"];  
                    List<CommonValue> list =(List<CommonValue>)form2.gridView.DataSource;  
                    list.AddRange(CV.ToArray());  
                    form2.gridView.DataSource = null;  
                    form2.gridView.DataSource = list;  
      
      
      
      
      
      
      
                }  
                  
      
            }  
        }  
      
        public class CommonValue  
        {  
            public string Colum1 { get; set; }  
      
            public string Colum2 {get; set; }  
      
            public string Column3 { get; set; }  
        }  
    

    Form2:

     public partial class Form2 : Form  
        {  
            public Form2()  
            {  
                InitializeComponent();  
            }  
            public DataGridView gridView  
            {  
                get  
                {  
                    return dataGridView1;  
                }  
                set  
                {  
                    dataGridView1 = value;  
                }  
            }  
      
              
        }  
    

    Tested result:

    239446-4.gif

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,551 Reputation points
    Sep 9, 2022, 10:23 AM

    One solution is to get checked rows in the main form, pass those rows to the child form and in the child form determine if that row exists, if not add it, if not do not add the row.

    • At no point in code do you need to touch the DataGridView other than casting it's DataSource to a DataTable in this case.
    • The base logic is dependent on using a hidden key which is not shown.

    Full source

    I created mocked data in a class method

    using System.Data;  
      
    namespace WinFormsApp1;  
      
    public class DataOperations  
    {  
        public static DataTable Table()  
        {  
            var dt = new DataTable();  
      
            dt.Columns.Add(new DataColumn() { ColumnName = "Process", DataType = typeof(bool), DefaultValue = false });  
      
            dt.Columns.Add(new DataColumn()  
            {  
                ColumnName = "Id",  
                DataType = typeof(int),  
                AutoIncrement = true,  
                AutoIncrementSeed = 1,  
                ColumnMapping = MappingType.Hidden  
            });  
      
            dt.Columns.Add(new DataColumn() { ColumnName = "FirstName", DataType = typeof(string) });  
            dt.Columns.Add(new DataColumn() { ColumnName = "LastName", DataType = typeof(string) });  
            dt.Columns.Add(new DataColumn() { ColumnName = "StartTime", DataType = typeof(DateTime) });  
      
            dt.Rows.Add(false, null, "Jeanine", "Abbott", new DateTime(2018, 1, 1, 8, 0, 0));  
            dt.Rows.Add(true, null, "Lester", "Lam", new DateTime(2018, 1, 1, 9, 0, 0));  
            dt.Rows.Add(false, null, "Claire", "Cowan", new DateTime(2018, 1, 1, 10, 0, 0));  
            dt.Rows.Add(false, null, "Karen", "Payne", new DateTime(2022, 1, 1, 10, 0, 0));  
      
            return dt;  
        }  
    }  
    

    Main form code

    using System.Data;  
      
    namespace WinFormsApp1;  
      
    public partial class Form1 : Form  
    {  
      
        private Form2 _form2;  
        public Form1()  
        {  
            InitializeComponent();  
      
            dataGridView1.DataSource = DataOperations.Table();  
        }  
          
        private void ProcessButton_Click(object sender, EventArgs e)  
        {  
      
            _form2 ??= new Form2();  
      
            if (_form2.IsDisposed)  
            {  
                _form2 = new Form2();  
            }  
              
            if (!_form2.Visible)  
            {  
                _form2.Top = 0;  
                _form2.Left = 0;  
                _form2.Show();  
            }  
      
            var checkedData = ((DataTable)dataGridView1.DataSource)  
                .AsEnumerable().Where(dataRow => dataRow.Field<bool>("Process")).ToList();  
      
            if (checkedData.Count <= 0) return;  
            {  
                var table = checkedData.CopyToDataTable();  
      
                foreach (DataRow row in table.Rows)  
                {  
                    _form2.Receive(row);  
                }  
            }  
        }  
    }  
    

    Child form code

    using System.Data;  
      
    namespace WinFormsApp1  
    {  
        public partial class Form2 : Form  
        {  
      
            public Form2()  
            {  
                InitializeComponent();  
                dataGridView1.DataSource = DataOperations.Table().Clone();  
            }  
      
            public void Receive(DataRow row)  
            {  
                var table = ((DataTable)dataGridView1.DataSource);  
                  
                var test = table.AsEnumerable()  
                    .FirstOrDefault(x => x.Field<int>("Id") == row.Field<int>("Id"));  
      
                if (test == null)  
                {  
                    table.ImportRow(row);      
                }  
      
            }  
        }  
    }  
      
    

    Screenshot

    239396-main1.png


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.