Laki
Laki

Reputation: 99

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.

Upvotes: 0

Views: 223

Answers (1)

Eugene Komisarenko
Eugene Komisarenko

Reputation: 1543

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.

Upvotes: 1

Related Questions