简体   繁体   中英

How to delete row from database depending on what is selected within a combobox

 private void DeleteClient_Load(object sender, EventArgs e)
    {
        try
        {
            connection = new SqlConnection(new DatabaseConnection().cnnString.ToString());
            connection.Open();
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.Message, "Could not establish connection to the database.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        cmd = new SqlCommand(new DatabaseAdd().addToComboBoxSE.ToString(), connection);

        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        foreach(DataRow dr in dt.Rows)
        {
            comboBox1.Items.Add(dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"]);
        }
        connection.Close();

    }

Here i am adding items to a comboBox from a database. I am adding the ID(int), FirstName(varchar) and Surname(varchar) to each item for each row in the database.

My question is, how do i go about deleting a row from the database depending on a list item i have selected within the comboBox? I am able to do it when i just add the ID(int) to the comboBox but since i need the id, firstname and surname, i am unable to retrieve the ID from whatever list option i have selected.

Any help is appreciated. Thank you.

Assuming that the Id is a numeric field, what you need to do is to split your string and extract the value of ID from the list. Since the format of the item is identical for all items, we can use the ". " as the separator string. So, you can write something like this:

var str = selectedItem; // this is the value of selected item from the combo box and it's type is string. Example: "123. John Doe"
int ID = 0;

var str = selectedItem.Trim(); // this is the value of selected item from the combo box and it's type is string
var index = selectedItem.IndexOf(". ");

if (index > 1)
{
    ID = Int32.Parse(selectedItem.Substring(0, index ) );                 
}

I was not sure if you're asking to remove a row from the ComboBox once selected then or delete from the db

This handles both, remove from Combo or delete from DB RowDeleter(string cmbName = "", bool deleteFromComboxBox )

Edit 1 updated the code based on comment:


    //added optional parameter to pass combobox value after successfully record operations, or just call it
    private void RowDeleter(ComboBox myComboBox)
    {
        try
        {
            SqlConnection conn = new SqlConnection(dataconnection);
            SqlCommand cmd = new SqlCommand("myconn", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "yourtableset");

            //look at what it is
            String selectedId = (ComboBoxItem)(myComboBox.SelectedItem).Value.ToString();
            DeleteRecord(selectedId);
            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }


    }

// delete Helper

private void DeleteRecord(string row)
{
  return if (StringIsNullOrEmpty(row))

    string sql = "DELETE FROM Table1 WHERE RowID = @row";

    SqlCommand deleteRecord = new SqlCommand();
    deleteRecord.Connection = someconnection;
    deleteRecord.CommandType = CommandType.Text;
    deleteRecord.CommandText = sql;

    SqlParameter RowParameter = new SqlParameter();
    RowParameter.ParameterName = "@RowID";
    RowParameter.SqlDbType = SqlDbType.string; //or int
    RowParameter.IsNullable = false;
    RowParameter.Value = row;

    deleteRecord.Parameters.Add(RowParameter);

    deleteRecord.Connection.Open();
    deleteRecord.ExecuteNonQuery();
    deleteRecord.Connection.Close();
    booksDataset1.GetChanges();

   // sqlDataAdapter1.Fill(someDataset.WHatverEmployees);

}

You need to create an instance of ComboBoxItem class and set its Value property to the id you want, then add it to your combobox.

The Class ComboBoxItem.cs:

public class ComboBoxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

Inside your foreach loop should be:

ComboBoxItem itm = new ComboBoxItem();
itm.Value = dr["Id"];
itm.Text = dr["Id"] + ". " + dr["FirstName"] + " " + dr["Surname"];
ComboBox1.Items.Add(itm);

You can get the selected item's id like this:

String selectedId = ((ComboBoxItem)(ComboBox1.SelectedItem)).Value.ToString();

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM