【问题标题】:How to delete row datagrid and update SQL database C#如何删除行数据网格并更新 SQL 数据库 C#
【发布时间】:2016-01-30 19:00:51
【问题描述】:

我真的被卡住了,这里的书籍或步骤都不够人性化,无法解释如何使用 C# 从数据网格对象中删除数据

从各种书籍和四个线程中,我设法得到了这个编码,但它无法执行 sql 命令,我有一个表调用'SpellingList',两列一是 ID,另一列是单词,我只想要做的是从数据网格中删除一行。

谁能给我指出正确的方向,一旦我解决了这个问题,我会上传一些简单易学的基本教程,以便其他新手可以按照这个示例进行操作。

我用过这个帖子How to delete a selected DataGridViewRow and update a connected database table?

和 MCSD Certificaiton Toolkit Exam 70-483 book Page 392 ,所有尝试都失败了。

如果我注释掉 if(dataGridView1.SelectedRows.Count > 0) 行,这里有一个 catch 22,我得到索引超出范围错误。

private void btnDelete_Click(object sender, EventArgs e)
{
     // My SQL connectionString 
         SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True");
        myConnection.Open();


        foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
        {

            if(dataGridView1.SelectedRows.Count > 0)
            {
                 int selectedIndex = dataGridView1.SelectedRows[0].Index;
                // gets the RowID from the first column in the grid
                int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());

                 // your code for deleting it from the database
                string sql = "DELETE FROM SpellingList WHERE Words =" + selectedIndex;
                SqlCommand deleteRecord = new SqlCommand();
                 deleteRecord.Connection = myConnection;
                 deleteRecord.CommandType = CommandType.Text;
                 deleteRecord.CommandText = sql;

                 SqlParameter RowParameter = new SqlParameter();
                 RowParameter.ParameterName = "@Words";
                 RowParameter.SqlDbType = SqlDbType.Int;
                 RowParameter.IsNullable = false;
                 RowParameter.Value = rowID;

                deleteRecord.Parameters.Add(RowParameter);

                deleteRecord.Connection.Open();

                deleteRecord.ExecuteNonQuery();
               if (oneCell.Selected)
                 dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
                deleteRecord.Connection.Close();

                wordsDataSet.GetChanges();
                // booksDataset1.GetChanges();
                spellingListTableAdapter.Fill(wordsDataSet.SpellingList);
            }// end of if 

            // then your code for refreshing the DataGridView
        }// end of for each statement 
        myConnection.Close();

}// end of delete Button 

【问题讨论】:

  • 最初如何填充网格?

标签: c# datagrid delete-row


【解决方案1】:

我们可以简化很多。并修复一些明显的错误。

ID 字段是表的关键字段,因此您应该使用它来查找要删除的行,然后,一个有用的参数需要在您要执行的命令文本中使用一个参数占位符

private void btnDelete_Click(object sender, EventArgs e)
{
     // No row selected no delete....
     if(dataGridView1.SelectedRows.Count == 0)
         return; // show a message here to inform

     // Prepare the command text with the parameter placeholder
     string sql = "DELETE FROM SpellingList WHERE ID = @rowID";

     // Create the connection and the command inside a using block
     using(SqlConnection myConnection = new SqlConnection("...."))
     using(SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
     {
        myConnection.Open();

        int selectedIndex = dataGridView1.SelectedRows[0].Index;
        // gets the RowID from the first column in the grid
        int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);

        // Add the parameter to the command collection
        deleteRecord.Parameters.Add("@rowID", SqlDbType.Int).Value = rowID;
        deleteRecord.ExecuteNonQuery();

        // Remove the row from the grid
        dataGridView1.Rows.RemoveAt(selectedIndex);
    }
}

如您所见,连接和命令是一次性对象,应包含在 using 语句中,以确保在出现异常时也能正确关闭和处理。

最后,从网格中删除行应该简单地使用行的索引来完成,在单个命令中删除行。您无需遍历单元格即可将它们一一删除。

【讨论】:

  • 感谢支持和代码示例,我已经测试了 SQL 脚本 "DELETE FROM SpellingList WHERE ID = @rowID"; ,这工作正常。在这个阶段唯一的问题是当你选择行并按下删除按钮时,什么也没有发生,注释掉那部分代码并再次编译代码,现在你最终出现索引超出范围的错误,和我有同样的问题以前的。我添加了这行代码来克服这个错误 if(dataGridView1.SelectedRows.Count > 0) ,现在即使我选择网格行,这个条件也永远不会实现。
  • MSDN 说:必须将 SelectionMode 属性设置为 FullRowSelect 或 RowHeaderSelect 才能使用选定的行填充 SelectedRows 属性。
【解决方案2】:

我要谦虚地感谢史蒂夫的贡献,如果没有像他这样的大师,我们这些新手可能会花费数小时来尝试解决一个简单而复杂的问题。

这是通过索引超出范围错误的少量修改的工作代码:

private void btnDelete_Click(object sender, EventArgs e)
    {

            // No row selected no delete....
           if(dataGridView1.SelectedRows.Count == 0)
           {

               MessageBox.Show("No row selected !");// show a message here to inform
           }


            // Prepare the command text with the parameter placeholder

           string sql = "DELETE FROM SpellingList WHERE ID = @rowID";


            // Create the connection and the command inside a using block
         using(SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True"))
         using (SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
         {
             myConnection.Open();

             MessageBox.Show("The SQL Connection is Open");

             // this overcomes  the out of bound error message 
             // if the selectedRow is greater than 0 then exectute the code below.
             if(dataGridView1.CurrentCell.RowIndex > 0)
             {

                int selectedIndex = dataGridView1.SelectedRows[0].Index;
                // gets the RowID from the first column in the grid
          int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);

                 // Add the parameter to the command collection
          deleteRecord.Parameters.Add("@rowID", SqlDbType.Int).Value = rowID;
          deleteRecord.ExecuteNonQuery();

                // Remove the row from the grid
                dataGridView1.Rows.RemoveAt(selectedIndex);
             }

         }

    }// end of delete Button 

请确保将 SelectionMode 的 datagrid 属性设置为“FullRowSelect”,因为 Steve 提到该属性将填充选定的行。

除以上内容外,这是针对新手的,请确保您将主键设置为具有整数值的 ID,在我的第一个错误中,我的主键中没有任何数据,它是 NULL 与一个字段 { Colum称为单词}。

在一周左右的时间内,我将发布有关如何创建简单数据库的分步指南,请注意这个空间。

【讨论】:

    猜你喜欢
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2012-07-12
    • 2017-11-06
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多