我有visual studio 2008和sql mgmt studio 2008 ...我创建了一个winform,我有一个组合框,显示在我的sql db中创建的所有表的名称,一个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);
}