C# SQL查询只运行一次

C# SQL查询只运行一次,c#,sql,sql-server,datagridview,C#,Sql,Sql Server,Datagridview,我有以下代码: 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.dataGridV

我有以下代码:

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();
SqlConnection con=newsqlconnection(@“Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True”);
字符串查询;
for(int i=0;i

它应该在表的每一列中插入一个特定的值(如dataGridView所示),但在保存第一个值(我们要插入的行的第一列中的值)后,它会刷新表,并且只插入第一个值。。。我想插入整行

代码按预期正确运行

这是您的代码:

for each column
 build sql string to take first row, current column and insert in db
 create sql command using the above sql string
 execute the above command
 refresh datagrid
next
上面的代码会产生您正在经历的确切行为,这是预期的,并且在某种意义上是正确的,因为代码完全按照要求执行

您的代码应基于您的描述:

for each row
 build base sql statement
 for each column
  add current value and field name to the base statement
 next
 create sql command
 fill the command with the statement built in the previous cycle
 execute the sql statement
next
refresh datagrid
如果只需插入一行,则不需要外部
foreach

在执行字符串连接以生成语句时,请注意输入清理和数据类型。

con.open()应该在循环外部

是否尝试将绑定移到
for
循环外部?我指的是这些行
BindingSource bSource=newbindingsource();bSource.DataSource=dt;dataGridView1.DataSource=bSource我已经试过了。。。这不好,这并不能回答这个问题。若要评论或要求作者澄清,请在其帖子下方留下评论-您可以随时在自己的帖子上发表评论,一旦有足够的评论,您就可以发表评论。我如何将当前值和字段名添加到基本语句中?我是否应该这样写:Query=“insert into[”+this.comboBox1.Text+”]([”,并在for each column to write Query+=…?在末尾使用两个单独的变量进行连接。在字段列表中使用一个变量,在值中使用另一个变量,并在末尾放入:
插入表(“+fields+”)值(“+values+”)
。不客气。如果这是最有用的答案,请将其标记为答案^^