2012-06-25 134 views
1

我在刪除搜索查詢返回的一行數據時遇到問題。 我希望用戶可以選擇任何一行數據,然後單擊刪除按鈕[button1_click]將其從數據庫中刪除。這是一個Windows窗體應用程序。從datagridview中刪除行

希望你能告訴我。非常感謝。 下面是我的代碼

public partial class Search : Form 
{ 
    public Search() 
    { 
     InitializeComponent(); 
     string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;"; 
     DataTable ds = new DataTable(); 
     using (var cn = new OleDbConnection(strConn)) 
     { 
      cn.Open(); 
      using (var cmd = new OleDbCommand("SELECT * FROM staff", cn)) 
      { 
       using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd)) 
        adp.Fill(ds); 

       comboBox1.DataSource = ds; 
       comboBox1.ValueMember = "sname"; 
       comboBox1.SelectedIndex = 0; 

      } 
     } 

    } 



    private void btn_search_bystaffname_Click(object sender, EventArgs e) 
    { 
     string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;"; 

     DataTable dt = new DataTable(); 

      using (var cn = new OleDbConnection(strConn)) 
      { 
       cn.Open(); 
       using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE sname = @sname", cn)) 
       { 
        //cmd.Parameters.AddWithValue("@bdate", dtp_search_date.Value.Date); 
        cmd.Parameters.AddWithValue("@sname", comboBox1.SelectedValue); 

        using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd)) 
         oda.Fill(dt); 
        GridView1.DataSource = dt; 

        GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
        GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
        GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
        GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
        GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
        GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 

        GridView1.Columns[0].HeaderText = "Booking ID"; 
        GridView1.Columns[1].HeaderText = "Client Name"; 
        GridView1.Columns[2].HeaderText = "Booking Date"; 
        GridView1.Columns[3].HeaderText = "Booking Time"; 
        GridView1.Columns[4].HeaderText = "Client Contact"; 
        GridView1.Columns[5].HeaderText = "Staff Name"; 

        this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12); 
        this.GridView1.DefaultCellStyle.ForeColor = Color.Blue; 
        this.GridView1.DefaultCellStyle.BackColor = Color.Beige; 
        this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow; 
        this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black; 

        this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
        this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
        this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
        this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
        this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
        this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 

       } 

      } 
     } 

    private void btn_search_bydate_Click(object sender, EventArgs e) 
    { 
     string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\DB_Booking.mdb;"; 

     DataTable dt = new DataTable(); 

     using (var cn = new OleDbConnection(strConn)) 
     { 
      cn.Open(); 
      using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = @bdate", cn)) 
      { 
       cmd.Parameters.AddWithValue("@bdate", dtp_search_date.Value.Date); 
       cmd.Parameters.AddWithValue("@sname", comboBox1.SelectedValue); 

       using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd)) 
        oda.Fill(dt); 
       GridView1.DataSource = dt; 

       GridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
       GridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
       GridView1.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
       GridView1.Columns[3].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
       GridView1.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 
       GridView1.Columns[5].HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter; 

       GridView1.Columns[0].HeaderText = "Booking ID"; 
       GridView1.Columns[1].HeaderText = "Client Name"; 
       GridView1.Columns[2].HeaderText = "Booking Date"; 
       GridView1.Columns[3].HeaderText = "Booking Time"; 
       GridView1.Columns[4].HeaderText = "Client Contact"; 
       GridView1.Columns[5].HeaderText = "Staff Name"; 

       this.GridView1.DefaultCellStyle.Font = new Font("Times New Roman", 12); 
       this.GridView1.DefaultCellStyle.ForeColor = Color.Blue; 
       this.GridView1.DefaultCellStyle.BackColor = Color.Beige; 
       this.GridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow; 
       this.GridView1.DefaultCellStyle.SelectionBackColor = Color.Black; 

       this.GridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
       this.GridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
       this.GridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
       this.GridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
       this.GridView1.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 
       this.GridView1.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter; 

      } 

     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
     DataGridViewRow row = GridView1.SelectedRows[0]; 
     GridView1.Rows.Remove(row); 

    } 

    } 

} 

回答

0

下面是我在我的應用程序已經做了(我對mysql表的唯一標識符是細胞零):

哦,dtcommand是一個類的實例一個數據庫命令類,我用於通用數據庫的東西。

 int userDeleteIndex; 
     if (int.TryParse(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), out userDeleteIndex)) 
     { 
      if (MessageBox.Show("Delete " + recordidentifyingdata + "? ", "Delete " + userDeleteIndex.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
      { 
       try 
       { 
        string updateUserSql = "DELETE FROM table WHERE user_id = " + userDeleteIndex.ToString() + "; "; 
        dtCommand.UpdateTable(updateUserSql); 
        InitializeUserDataView(); 
        // Initalize userdataview refreshes the datagridview with the updated info 
       } 
       catch (Exception err) 
       { 
        Error trapping goes here 
       } 

下面是從我的類數據庫更新部分:

public int UpdateTable(string updateString, string MySqlConnectionString) 
{ 
    int returnValue = 0; 
    MySqlConnection connection = new MySqlConnection(MySqlConnectionString); 
    MySqlCommand command = new MySqlCommand(updateString, connection); 
    try 
    { 
     connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
    catch (Exception err) 
    { 
     WriteErrorLog("Unable to update table: " + err.ToString() + 
      " - Using SQL string: " + updateString + "."); 
     //MessageBox.Show("An error has occured while updating the database.\n" + 
     //"It has been written to the file: " + errorFile + ".", "Database Error"); 
     returnValue = -1; 
    } 
    finally 
    { 
     connection.Close(); 
    } 
    return (returnValue); 
} 
2

我假設這是你想改變

private void button1_Click(object sender, EventArgs e) 
{ 
    GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
    DataGridViewRow row = GridView1.SelectedRows[0]; 
    GridView1.Rows.Remove(row); 

} 

GridView1.Rows.Remove(row);將只刪除項目的方法DaDataGridViewRowCollection並不會將其從數據庫中刪除。

從數據庫中刪除它,你可以做以下

  1. 從`數據表」中取出一個,然後使用DataAdapter和呼叫更新。

  2. 通過OleDbCommand使用DELETE SQL語句直接從數據庫中刪除它。

如果您選擇第一個選項,您可以通過在表單上設置dt字段來滿足您的需求。這是因爲您現在只能通過button1_Click事件中的((DataRow)row.DataBoundItem).TableGridView1.DataSource來訪問它。另外使DataAdapter成爲一個字段將使得這更容易,例如,

GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
DataGridViewRow row = GridView1.SelectedRows[0]; 
DataRow dRow = (DataRow)row.DataBoundItem; 
dt.Rows.Remove(dRow); 
Adapter.Update(dt); 

順便說一句,你可以選擇做只在的button1_Click的dt.Rows.Remove(dRow);和推遲Adapter.Update(dt),直到後來在保存按鈕。

如果使用方案二去,你會需要從數據表刪除或刷新數據表

例如

GridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; 
DataGridViewRow row = GridView1.SelectedRows[0]; 

OleDbCommand cmd = new OleDbCommand( 

using (var cn = new OleDbConnection(strConn)) 
{ 
    cn.Open(); 
    // not 100% this delete syntax is correct for Access 
    using (var cmd = new OleDbCommand("DELETE booking WHERE [Booking ID] = @BookingId", cn)) 
    { 
     cmd.Parameters.AddWithValue("@BookingId", dRow["Booking Id"]); 
     cmd.ExecuteNonQuery();  
    } 
} 

// Do this to update the in-memory representation of the Data 
DataRow dRow = (DataRow)row.DataBoundItem; 
dt.Rows.Remove(dRow); 

// Or just refresh the datatable using code similar as your search methods