将数据表从一个表单传递到另一个表单

时间:2016-07-06 13:09:41

标签: c# sql

我有一个form1和form2。 Form2从form1打开,填充后有一个dgv,它被复制到单击按钮上的数据表,form2关闭或者可见= false。我将数据表传递给form1,但它给了我一个空引用。这是我在form2中的代码:

private void button1_Click(object sender, EventArgs e)
        {
            perclothesdescriptionDT = new DataTable();

            foreach (DataGridViewColumn col in dataGridView3.Columns)
            {
                perclothesdescriptionDT.Columns.Add(col.HeaderText);
            }

            foreach (DataGridViewRow row in dataGridView3.Rows)
            {
                DataRow dRow = perclothesdescriptionDT.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dRow[cell.ColumnIndex] = cell.Value;
                }
                perclothesdescriptionDT.Columns.RemoveAt(0);
                perclothesdescriptionDT.Rows.Add(dRow);
            }
            this.Visible = false;

        }

        public DataTable mydt
        {
            get
            {
                return perclothesdescriptionDT;
            }
        }

在form1中:

form2= new Form2();

                cmd1.CommandText = "insert into [dbo].[personClothesDesc](upperPart, lowerPart, belt, socks, shoes, differentSigns) values (@upperPart, @lowerPart, @belt, @socks, @shoes, @differentSigns)";
                        for (int i = 0; i < form2.mydt.Rows.Count; i++)
                        {
                            cmd1.Parameters.Clear();
                            cmd1.Parameters.AddWithValue("@upperPart", form2.mydt.Rows[i].ItemArray.GetValue(5).ToString());
                            cmd1.Parameters.AddWithValue("@lowerPart", form2.mydt.Rows[i].ItemArray.GetValue(4).ToString());
                            cmd1.Parameters.AddWithValue("@belt", form2.mydt.Rows[i].ItemArray.GetValue(3).ToString());
                            cmd1.Parameters.AddWithValue("@socks", form2.mydt.Rows[i].ItemArray.GetValue(2).ToString());
                            cmd1.Parameters.AddWithValue("@shoes", form2.mydt.Rows[i].ItemArray.GetValue(1).ToString());
                            cmd1.Parameters.AddWithValue("@differentSigns", form2.mydt.Rows[i].ItemArray.GetValue(0).ToString());
                            cmd1.ExecuteNonQuery();
                        }

0 个答案:

没有答案