combobox and dbkey reference

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DragonLord
    New Member
    • Mar 2007
    • 122

    combobox and dbkey reference

    I have may situations where I want to load into a combo box a list of products by name but I want to be able to run a query with the corresponding id in the database so when the user picks red wagon i can fire an event that will do something with the database and it knows that red wagon is idkey in the database is 12 or if they pick yellow truck it is idkey 51 etc.

    I know how to load the list box with a list of descriptions from the database but i am not sure how to associate the idkey at the same time to that list item and then pull it out later.

    any help would be greatly appreciated.


    thanks in advance.
  • mldisibio
    Recognized Expert New Member
    • Sep 2008
    • 191

    #2
    For the WebControl ListBox, each added item has a Text and Value property, so your id would be the value of the selected item.
    Code:
    myListBox.Items.Add(new ListItem("FireTruck", "51"));
    For the Windows.Form ListControl and derivatives you either add an object or bind to a list of objects. In this case you specify a property of the object that serves as the ListControl.Dis playMember and a property which serves as the ValueMember.

    So when you pull your data from the database, you can put the values into a "business object" called Product.

    Code:
    class Product{
     string productName;
     int productId;
    
     public Product(string name, int id){
       this.productName = name;
       this.productId = id;
     }
     public string ProductName{get{return this.productName;}}
     public int ProductId{get{return this.productId;}}
    }
    
    ListControl ctl = new ListBox();
    // In real code, you create a List<Product> from the database
    // and bind the control to the list
    ctl.Items.Add(new Product("FireTruck", 51));
    // etc
    ctl.DisplayMember = "ProductName";
    ctl.ValueMember = "ProductId";
    Use the SelectedValue property to get the ProductId of the Product whose name is displayed and which the user has chosen.

    See ListControl.Val ueMember Property (System.Windows .Forms)

    Comment

    • DragonLord
      New Member
      • Mar 2007
      • 122

      #3
      Ok that makes perfect sense thank you, maybe you can help me with one other thing.

      What I am doing is trying to contain all my data access to one project and pass back items to the main application.

      To clarify in the above situation i would send a query to the database such as "Select Description, productid from products" my question is should i just make use of the poduct class and make a list<product> and pass that back so that i can populate the combobox with the data.

      I am basically loading data based on a selected account and the products available and allowing the client to pick that item from a drop down list then go and do pricing and update inventory.

      so is that the best way to d it, pass the list<product> back then itterate through it to populate the combo box?

      Comment

      • mldisibio
        Recognized Expert New Member
        • Sep 2008
        • 191

        #4
        You are thinking in the right direction - keep it up!
        What you are driving for is an "n-tiered" application implementing Object Oriented design principles.
        At a very high level, your app would consist of:
        • a strict "database layer" - talks only to the database, knows nothing about "Product"
        • a "business layer" - knows about Product, but doesn't care about what database it comes from
        • a "presentati on layer" - knows how to display a list of Products, doesn't care where they came from.


        So one way to do this is to
        • have your database layer simply return a query result (such as a DataSet or DataReader) with the results of "SELECT * FROM Products" or whatever.
        • Your business layer would call the database layer, specifying the sql or stored procedure to execute, and loop through the DataReader result to create a list of Products.
        • Your UI layer would call the business layer and get the List<Products> as a return value, and simply display them.


        You can google any of the above key words to get some great tutorials and explanations. Also look up "Model-View-Controller." Here is a link that I find very simple to follow and has a simple but realistic example (The article has three parts)
        CodeProject: ADO.NET for the Object-Oriented Programmer – Part One. Free source code and programming help

        Comment

        • DragonLord
          New Member
          • Mar 2007
          • 122

          #5
          Ok having a bit of a problem, need some more help. I created a list of items

          Code:
          public List<DBHelperDescValue> getListDescValue(String cmdString)
                  {
                      myConnection.Open();
                      List<DBHelperDescValue> myList = new List<DBHelperDescValue>();
                      SqlCommand myReaderCMD = new SqlCommand(cmdString, myConnection);
                      SqlDataReader _ListDataReader = myReaderCMD.ExecuteReader();
                      while (_ListDataReader.Read())
                      {
                          myList.Add( new DBHelperDescValue (_ListDataReader[0].ToString(),Convert.ToInt32(_ListDataReader[1])));
                        
                      }
                      myConnection.Close();
                      return myList;
                  }
          then I pass that back and I would like to ad this to the combobox now.

          Code:
           loadPackages.ForEach(delegate(DBHelperDescValue dbhDV)
                     {
                         cboPackages.Items.Add(dbhDV.ItemDescription);
                         cboPackages.ValueMember = dbhDV.ItemValue.ToString();
                     });
          the idea here is i want to us a combobox due to space and gui design and when i select box it knows the database id. however when i test this i always see 9 wich is the id for the item i added last.

          Any thoughts would be appreciated.

          Comment

          • mldisibio
            Recognized Expert New Member
            • Sep 2008
            • 191

            #6
            First of all, ValueMember should be set only once. It means "Use the property of my object with this name("ItemValue ") as the value for each item I add to the Items collection." (Same for DisplayMember).
            Secondly, using this pattern, you add the entire object to the Items collection, not just the display string.
            Code:
            cboPackages.ValueMember = "ItemValue";
             loadPackages.ForEach(delegate(DBHelperDescValue dbhDV)
                       {cboPackages.Items.Add(dbhDV);});
            ...using your syntax to illustrate...bu t this still will not work correctly.

            Apparently you can only set ValueMember and DisplayMember if you actually bind a source collection to the ListBox.
            Code:
            cboPackages.DataSource = loadPackages; // (the List, I assume)
            cboPackages.ValueMember = "ItemValue";
            cboPackages.DisplayMember = "ItemDescription";
            Then, you don't even need to loop through and add each item.

            I almost always bind to a collection as a DataSource, so it did not occur to me in my original post that those two properties will not work correctly if you are just adding items to the ListBox without data binding. Apologies.
            If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object.

            Comment

            • DragonLord
              New Member
              • Mar 2007
              • 122

              #7
              Thanks this worked Great, even aloud me to get rid of some redundant code that cleared the list from the combobox. It is also going to make it so much easier to take make use of multiple linked comboboxes.

              Thanks ever so much.

              Comment

              Working...