【发布时间】:2015-10-17 10:39:48
【问题描述】:
我有以下代码:
SqlConnection con = new SqlConnection(@"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
String Query;
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
MessageBox.Show(" " + this.dataGridView1.Columns.Count);
MessageBox.Show(" " + this.dataGridView1.Columns[i].Name + " ");
MessageBox.Show(" " + this.dataGridView1.SelectedRows[0].Cells[i].Value + " ");
Query = "insert into [" + this.comboBox1.Text + "] ([" + this.dataGridView1.Columns[i].Name + "]) Values ('" + this.dataGridView1.SelectedRows[0].Cells[i].Value + "') ;";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(Query, con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
}
con.Close();
它应该在表的每一列中插入一个特定的值(显示在 dataGridView 中),但是在保存第一个值(我们要插入的行的第一列的值)之后,它会刷新表并只有第一个值被插入...我想插入整行
【问题讨论】:
-
您是否尝试将绑定移出
for循环?我指的是这些行BindingSource bSource = new BindingSource(); bSource.DataSource = dt; dataGridView1.DataSource = bSource; -
我试过了……不行
标签: c# sql sql-server datagridview