【问题标题】:SQL Query runs only onceSQL 查询只运行一次
【发布时间】: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


【解决方案1】:

代码运行正常。

这是你的代码:

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
在执行字符串连接以构建语句时,会处理输入清理和数据类型。

【讨论】:

  • 如何将添加当前值和字段名称添加到基本语句中?我应该这样写:Query = "insert into [" + this.comboBox1.Text + "] ([", 并在每一列中写 Query += ... ?
  • 最后使用 2 个单独的变量加入。为字段列表使用一个变量,为值使用另一个变量,最后输入:"INSERT INTO table (" + fields + ") VALUE (" + values + ")"。
  • 不客气。如果这是最有帮助的答案,请将其标记为答案 ^^
【解决方案2】:

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

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post。
猜你喜欢
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
相关资源
最近更新 更多