2012-06-25 4 views
1

검색 쿼리에서 반환 한 데이터 행을 삭제하는 데 문제가 있습니다. 사용자가 원하는 데이터 행을 선택하고 [button1_click] 삭제 버튼을 클릭하여 DB에서 삭제할 수 있기를 바랍니다. 이것은 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이의 클래스 인스턴스 공통 DB 물건에 사용하는 데이터베이스 명령 클래스. 여기

 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을 제거하고 데이터베이스에서 제거하지 않습니다.

는`DataTable에 '에서 제거 다음

  1. 중 하나를 수행 한 다음 데이터 어댑터와 전화 업데이 트를 사용할 수있는 데이터베이스에서 제거합니다.

  2. OleDbCommand를 통해 DELETE SQL 문을 사용하여 데이터베이스에서 직접 삭제하십시오.

옵션 1을 선택하면 dt을 양식에 입력하면됩니다. button1_Click 이벤트에서 또는 GridView1.DataSource을 통해서만 액세스 할 수 있기 때문입니다. 또한 DataAdapter를 필드로 만들면 더 쉽게 만들 수 있습니다.

예 : 옆으로 당신이를 Button1_Click만을 dt.Rows.Remove(dRow);을 수행하고 저장 버튼 나중에까지 Adapter.Update(dt)을 연기하도록 선택할 수 있습니다으로

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

. 이 옵션이 갈 경우

당신은 DataTable을

예를 DataTable의에서 제거하거나 새로 고침해야합니다

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 
관련 문제