0

私はVisual Studio 2008とSQL mgmt Studio 2008を持っています...私はwinformを作成し、SQLデータベースで作成されたすべてのテーブルの名前を示すコンボボックス、dgv、およびボタンを持っています...今、データを挿入したいdgvの複数の新しい行で、SQLデータベースに自動的に保存します...これが私のコードのスニペットです-

コード:

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

0 に答える 0