如何在网格视图中插入多个数据

时间:2013-04-02 10:01:46

标签: c# vb.net winforms sql-server-2008 visual-studio-2008

我有visual studio 2008和sql mgmt studio 2008 ...我创建了一个winform,我有一个组合框,显示在我的sql db中创建的所有表的名称,一个dgv和一个按钮...... 现在我想在dgv的多个新行中插入数据并将其自动保存在我的sql db中......这是我的代码中的snipet -

代码

    private void InsertInfo()
    {

        string table = comboBox1.Text;
        string connectionString = null;
        SqlConnection connection;
        SqlDataAdapter adapter = new SqlDataAdapter();

        connectionString = @"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";

        connection = new SqlConnection(connectionString);

        //if (comboBox1.Text == "lol")
        //{
        //    string insrtQry = "INSERT INTO lol (name, marks) VALUES (@value1, @Value2)";
        //}
        //else
        //{
        //    string insrtQry = "INSERT INTO datejoin (first name,last name,date joined) VALUES (@value1, @value2,@value3)";


        //}
        foreach (int rowIndex in lstNewRows)
        {


            string insrtQry = "insert into " + comboBox1.Text + " values(";

            foreach (DataGridViewCell cell in dataGridView1.Rows[rowIndex].Cells)
            {
                insrtQry += "'" + cell.Value.ToString() + "',";
            }

            insrtQry = insrtQry.TrimEnd(",".ToCharArray());

            insrtQry += ")";


            try
            {
                connection.Open();
                adapter.InsertCommand = new SqlCommand(insrtQry, connection);
                adapter.InsertCommand.ExecuteNonQuery();



                MessageBox.Show("Row inserted !! ");
                connection.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

        private void insert_Click(object sender, EventArgs e)
        {
            InsertInfo();
        }
 private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            lstNewRows.Add(e.Row.Index);
        }

0 个答案:

没有答案