Search code examples
c#linqcombobox

how to get the value member of a selected comboBox to use it to add a new object with linq


I'am tring to make a new object with linq and add it to my database. The value of the category and supplier is selected from a comboBox. The comboBox DataSource is from the database(I used linq)and so is the DisplayMember and the Valuemember.I can't get the value (valueMember)of the selected comboBox to use it on to make the new object. I can't understand what is the problem.

This is my code:

 DataClasses1DataContext db = new DataClasses1DataContext();
    bool lo;

    public Form2()
    {
        InitializeComponent();
        lo = false;

        var category = from Category in db.Categories
                       select new
                      {
                           categorytName = Category.CategoryName,
                           categoryID = Category.CategoryID
                      };

        comboBox1.DataSource = category;
        comboBox1.DisplayMember = "categorytName";
        comboBox1.ValueMember = "categoryID";

        var supplier = from Supplier in db.Suppliers
                       select new
                       {
                           suppliertName = Supplier.CompanyName,
                           supplierID = Supplier.SupplierID
                       };

        comboBox2.DataSource = supplier;
        comboBox2.DisplayMember = "suppliertName";
        comboBox2.ValueMember = "supplierID";
        lo = true;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Create a new product.
        Product newProduct = new Product
        {
            ProductName = textBox1.Text,
            UnitPrice = Convert.ToDecimal(textBox2.Text),
            CategoryID = comboBox2.ValueMember,
            //SupplierID = Convert.ToInt32(comboBox1.Text)
        };

        // Add the new object to the product collection.
        db.Products.InsertOnSubmit(newProduct);

        //Submit all changes.
        db.SubmitChanges();

    }

Solution

  • Replace:

    comboBox2.ValueMember
    

    With:

    comboBox2.SelectedValue