My form1 has a datagridview that is being populated by a dataset. I need to get the row's values selected on the datagridview to another form, which is form2 that is consist of textboxes. I am quite confused whether to pass the dataset to form2 or use a datareader to read the passed primary key value and assign the values to the textboxes.

I did an example code which populates dgv from a dataSet, and then gets the selected row`s data, and passed them to form2`s textBoxes. In my example I only have 2 column in the dataSet (as in dgv of course) and 2 textBoxes to populate on form2.
Take a look, and let me know its any good.
Code:

//form1:
        DataSet ds;
        public Form1()
        {
            InitializeComponent();

            ds = new DataSet();
            DataTable table = new DataTable("myTable");
            table.Columns.Add("column 1", typeof(string));
            table.Columns.Add("column 2", typeof(int));
            DataRow dr;

            //creating some example data to populate dgv:
            for (int i = 0; i < 10; i++)
            {
                dr = table.NewRow();
                dr["column 1"] = "Some name " + (i + 1);
                dr["column 2"] = i * 2;
                table.Rows.Add(dr);
            }
            ds.Tables.Add(table);

            //set dgv:
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //bind dataSet to dgv:
            dataGridView1.DataSource = new BindingSource(ds.Tables["myTable"], null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<object> list = new List<object>();
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
                foreach (DataGridViewCell cell in row.Cells)
                    list.Add(cell.Value);

            Form2 f2 = new Form2();
            f2.GetDataFromForm1(list);
            f2.Show(this);
        }
    }    

//form2:
//I have decided to create a new method, which will be called from form1 (instead of it, the data can be passed into the constructor of form2 in the same way).
    public partial class Form2 : Form
    {
        public Form2()
        {
            //constructor of form2
            InitializeComponent();
        }

        public void GetDataFromForm1(List<object> data)
        {
            textBox1.Text = data[0].ToString();
            textBox2.Text = data[1].ToString();
        }
    }

Hope it helps,
Mitja

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.