繁体   English   中英

如何根据组合框中选择的内容从数据库中删除行

[英]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();

    }

在这里,我将项目从数据库添加到comboBox。 我将ID(int),FirstName(varchar)和Surname(varchar)添加到数据库中每一行的每个项目。

我的问题是,如何根据我在comboBox中选择的列表项从数据库中删除行? 当我只将ID(int)添加到comboBox时,我就能做到这一点,但是由于我需要ID,名字和姓氏,因此我无法从我选择的任何列表选项中检索ID。

任何帮助表示赞赏。 谢谢。

假设Id是一个数字字段,您需要做的是拆分字符串并从列表中提取ID的值。 由于所有项目的项目格式都相同,因此我们可以使用". "作为分隔字符串。 因此,您可以编写如下内容:

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

我不确定您是否要选择一次从ComboBox中删除一行,然后从数据库中删除

这既可以处理,也可以从组合中删除,也可以从数据库 RowDeleter(string cmbName = "", bool deleteFromComboxBox )

编辑1根据注释更新了代码:


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


    }

// 删除助手

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

}

您需要创建一个ComboBoxItem类的实例,并将其Value属性设置为所需的ID,然后将其添加到组合框。

ComboBoxItem.cs类:

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

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

在您的foreach循环内应该是:

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

您可以像这样获取所选商品的ID:

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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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