簡體   English   中英

C# - 如何從DataGridView中刪除選定的行?

[英]C# - How to delete selected rows from a DataGridView?

我試圖刪除用戶在C#WinForms應用程序中的DataGridView中選擇的行(連接到已有記錄的本地數據庫)。

我已經實現了下面的代碼,並且沒有錯誤,但是從不拾取刪除(即使消息框顯示記錄已被“刪除”,這不是真的,因為記錄保留在DataGrid中)

另請注意,刪除功能在搜索功能中 - 請參閱下面的代碼。

public void DisplayData()
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        string Query = "select * from Customers";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(DBCommand);
            da.Fill(dt);
            dgv_CustomerDetails.DataSource = dt;
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
        }
    }


    private void SearchCustomerRecordForm_Load(object sender, EventArgs e)
    {
        DisplayData();
    }


    private void btnDeleteCustomerRecord_Click(object sender, EventArgs e)
    {
        string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename= C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf ;Integrated Security=True;Connect Timeout=30";

        int rowIndex = dgv_CustomerDetails.CurrentCell.RowIndex;

        string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex) +"'";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DBReader = DBCommand.ExecuteReader();
            MessageBox.Show("Customer record removed from the system.", "Library System", MessageBoxButtons.OK);
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();
            DisplayData();
        }
    }

你確定查詢創建得好嗎? 似乎該行中缺少Cell Value屬性:

string Query = "delete from Customers where CustomerName = '"+ dgv_CustomerDetails.CurrentCell(rowIndex).value +"'";

嘗試查看Query變量的值,因為它已構建起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM