简体   繁体   中英

How to get value from combo box by passing its ValueMember

I have a simple database with 2 tables (product and category) and the code below is to create a new product in the product table under one of the categories selected in the combo box.

public partial class frmAddProduct : Form
    {
        public frmAddProduct()
        {
            InitializeComponent();

            db = new DatabaseEntities();
        }

        DatabaseEntities db;
        string category = "";
        Product _product;

        private void frmAddProduct_Load(object sender, EventArgs e)
        {
            categoryBindingSource.DataSource = db.Categories.ToList();
            CategoryList();
        }

        private void CategoryList()
        {
            var list = db.Categories.ToList();
            cboCategory.DataSource = list;
            cboCategory.DisplayMember = "CategoryName";
            cboCategory.ValueMember = "CategoryID";

            if (cboCategory.Items.Count > 1)
                cboCategory.SelectedIndex = -1;
        }

        private void btnNew_Click_1(object sender, EventArgs e)
        {
            _product = new Product();

            int id = int.Parse(txtID.Text);
            decimal price = decimal.Parse(txtPrice.Text);
            int qty = int.Parse(txtPrice.Text);

            _product.ProductID = id;
            _product.ProductName = txtName.Text;
            _product.UnitPrice = price;
            _product.UnitsInStock = qty;
            _product.CategoryID = int.Parse(category);

            db.Products.Add(_product);
            db.SaveChanges();
        }

        private void cboCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            category = cboCategory.SelectedValue.ToString();
        }
    }

When I run the form an error appears saying "Additional information: Object reference not set to an instance of an object". The error refers to the next line in the code:

category = cboCategory.SelectedValue.ToString();

Does anyone know what is the problem here?

One note: CategoryID is an integer field in the database.

It looks like your setting of the SelectedIndex to -1 is triggering SelectedIndexChanged event with nothing in SelectedValue which you are trying to read in the handler. You might be missing check for null in the handler.

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