0

我正在尝试使用 c# 和 psql 将数据绑定到组合框。但是,当我将数据添加到数据库时,我无法让组合框自动更新。

这就是我将组合框绑定到数据库的方式:

private void bindProductComboBox(ComboBox box)
    {
        box.DataSource = allProducts;
        box.ValueMember = "product_id";
        box.DisplayMember = "name";
    }

allProducts 是一个私有 DataTable,它接收数据库中的所有产品。

这是我的 ProductModel 类

public class ProductsModel : INotifyPropertyChanged
{

    private DatabaseConnector db = new DatabaseConnector();
    private DbConnection conn = null;
    private Helper helper = new Helper();

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged([CallerMemberName] String caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }

    public void Add(String partCode, String name, Int16 supplier, Decimal unitCost)
    {
        using (this.conn = this.db.OpenConnection())
        {
            string statement = "INSERT INTO products ( part_code, name, supplier, unit_cost )" +
                               "VALUES ( @partCode, @name, @supplier, @unitCost )";
            DbCommand cmd = this.helper.initializeCommand(this.conn, statement);

            this.helper.createStringParam(cmd, "@partCode", partCode);
            this.helper.createStringParam(cmd, "@name", name);
            this.helper.createInt16Param(cmd, "@supplier", supplier);
            this.helper.createDecimalParam(cmd, "@unitCost", unitCost);

            cmd.Prepare();
            cmd.ExecuteNonQuery();
            RaisePropertyChanged();
        }
    }

    public DataTable GetAll()
    {
        using (this.conn = this.db.OpenConnection())
        {
            String statement = "SELECT * FROM products";
            DbCommand cmd = this.helper.initializeCommand(this.conn, statement);

            cmd.Prepare();
            DbDataReader reader = cmd.ExecuteReader();

            DataTable table = new DataTable();
            table.Columns.Add("product_id", typeof(Int16));
            table.Columns.Add("name", typeof(String));
            table.Load(reader);

            return table;
        }
    }
}

我不确定我是否正确实现了 INotifyPropertyChanged 接口。

4

0 回答 0