1

I having problem on deleting a row of data returned by a search query. I wish the user can select whichever row of data and click on the delete button [button1_click] to delete it from DB. This is a windows form application.

Hope you can advise me. Thanks a lot. Below is my code

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);

    }

    }

}

2 Answers 2

2

I'm assuming this is the method you want to change

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

}

This GridView1.Rows.Remove(row); will only remove the item from the DaDataGridViewRowCollection and will not remove it from the database.

To remove it from the database you can do one of the following

  1. Remove it from `DataTable' and then use a DataAdapter and call update.

  2. Directly delete it from the database using a DELETE SQL statement through a OleDbCommand.

If you choose option one you'd be well served by making dt a Field on your Form. This is because you can only access it now via ((DataRow)row.DataBoundItem).Table or GridView1.DataSource in the button1_Click event. Also making the DataAdapter a field would make this easier

e.g.

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

As an aside you can choose to do only the dt.Rows.Remove(dRow); in the button1_Click and defer the Adapter.Update(dt) until later in a Save button.

If you go with option two you'll need to remove it from the DataTable or refresh the DataTable

e.g.

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 
0

Here's how I've been doing it in my application (My unique identifier for the mysql table is in cell zero):

Oh, and dtcommand is a class instance for a database command class I use for common db stuff.

        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
                }

Here's the database update section from my class:

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.