【问题标题】:Get selected dataGridView column data?获取选中的dataGridView列数据?
【发布时间】:2014-09-20 07:52:48
【问题描述】:

C# Windows 窗体

我有一个从 dataGridView 中删除选定行的按钮。 我还希望该按钮能够检索选定行的“orderre”列值,因此我可以在从 sql 表中删除订单的查询中使用它。

我的代码如下所示:

                    dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                    //SQL connection
                    SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
                    SqlCommand command = con.CreateCommand();

                    //SQL QUERY
                    command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = @ordre";
                    command.Parameters.AddWithValue("@ordre",dataGridView1.SelectedRows[0].Cells["ordre"].Value.ToString())

                    con.Open();
                    var ordre = command.ExecuteScalar();
                    con.Close();

但它不起作用!没有记录被删除

【问题讨论】:

    标签: c# sql winforms datagridview get


    【解决方案1】:

    删除行后无法获取值。所以像这样改变你的代码

     //SQL connection
    SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt 
    + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security
    Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
    SqlCommand command = con.CreateCommand();
    
    //SQL QUERY
    command.CommandText = "DELETE FROM bestillinger WHERE ordrenr = @ordre";
    command.Parameters.AddWithValue("@ordre",dataGridView1.
    SelectedRows[0].Cells["ordre"].Value.ToString())
    
    con.Open();
    var ordre = command.ExecuteScalar();
    con.Close();
    dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
    

    【讨论】:

      【解决方案2】:

      这是错误的逻辑。

      由于该行已被 RemoveAt() 删除,

      你不能从 dataGridView1.SelectedRows[0] 得到错误的行。

      【讨论】:

        【解决方案3】:

        我想你想要这个。

          private void grdform1_CellClick(object sender, DataGridViewCellEventArgs e)
                 {  
                 If(e.ColumnIndex==0 ||e.ColumnIndex==1)
                  {
                   txtshowcolunm.text=e.ColumnIndex;
                      }
                    else
                    {
                  txtshowcolunm.text=e.ColumnIndex;
                }
                   }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 2018-12-30
          • 1970-01-01
          • 2020-07-09
          • 2013-04-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多