在C#中将数据绑定到组合框

时间:2013-08-19 04:40:08

标签: c# visual-studio-2012 psql

我正在尝试使用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接口。

0 个答案:

没有答案