从BindingContext中移除选中的项目

本文关键字:项目 BindingContext | 更新日期: 2023-09-27 18:15:33

给定以下代码:

 DialogResult result3 = MessageBox.Show("Proceed With Checkout?", "Request Granted",
    MessageBoxButtons.YesNoCancel,
    MessageBoxIcon.Question,
    MessageBoxDefaultButton.Button2);
                if (result3 == DialogResult.Yes)
                {
                    int delete = int.Parse("s_NTextBox.Text");
                    this.BindingContext[iTEMDataSet, "ITEM"].RemoveAt(0);
                }
                if (result3 == DialogResult.No)
                {
                    //quantity = quantity - 1;
                    //quantityTextBox.Text = Convert.ToString(quantity);
                }
            }
            catch
            {
                MessageBox.Show("error");
            }
        }

this.BindingContext[iTEMDataSet, "ITEM"].RemoveAt(0)行,我想删除当前选中的项目。当前代码总是删除第一项。如何做到这一点?

从BindingContext中移除选中的项目

使用Position属性

this.BindingContext[iTEMDataSet, "ITEM"].
    RemoveAt(this.BindingContext[iTEMDataSet, "ITEM"].Position);

我知道你要从数据库中删除一条记录,该记录与文本框中给定的ID相匹配。

所以,只要写下面的代码如果对话sult。Yes is true

        int numberOfRowsAffected = 0;
        bool isDeleted = false;
        string query = @"DELETE FROM targetTable WHERE ID=@ID";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = query;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.Add(new SqlParameter("@ID", deletedItemID));
        try
        {
            using (SqlConnection cn = new SqlConnection(ConnectionString))
            {
                cmd.Connection = cn;
                cn.Open();
                object result = cmd.ExecuteNonQuery();
                isDeleted = Convert.ToInt32(result) > 0 ? true : false;
            }
        }
        catch (Exception ex)
        {
            isDeleted = false;
        }