473,325 Members | 2,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

combobox and dbkey reference

122 100+
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.
Jan 15 '09 #1
6 1621
mldisibio
190 Expert 100+
For the WebControl ListBox, each added item has a Text and Value property, so your id would be the value of the selected item.
Expand|Select|Wrap|Line Numbers
  1. 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.DisplayMember 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.

Expand|Select|Wrap|Line Numbers
  1. class Product{
  2.  string productName;
  3.  int productId;
  4.  
  5.  public Product(string name, int id){
  6.    this.productName = name;
  7.    this.productId = id;
  8.  }
  9.  public string ProductName{get{return this.productName;}}
  10.  public int ProductId{get{return this.productId;}}
  11. }
  12.  
  13. ListControl ctl = new ListBox();
  14. // In real code, you create a List<Product> from the database
  15. // and bind the control to the list
  16. ctl.Items.Add(new Product("FireTruck", 51));
  17. // etc
  18. ctl.DisplayMember = "ProductName";
  19. 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.ValueMember Property (System.Windows.Forms)
Jan 16 '09 #2
DragonLord
122 100+
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?
Jan 16 '09 #3
mldisibio
190 Expert 100+
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 "presentation 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
Jan 16 '09 #4
DragonLord
122 100+
Ok having a bit of a problem, need some more help. I created a list of items

Expand|Select|Wrap|Line Numbers
  1. public List<DBHelperDescValue> getListDescValue(String cmdString)
  2.         {
  3.             myConnection.Open();
  4.             List<DBHelperDescValue> myList = new List<DBHelperDescValue>();
  5.             SqlCommand myReaderCMD = new SqlCommand(cmdString, myConnection);
  6.             SqlDataReader _ListDataReader = myReaderCMD.ExecuteReader();
  7.             while (_ListDataReader.Read())
  8.             {
  9.                 myList.Add( new DBHelperDescValue (_ListDataReader[0].ToString(),Convert.ToInt32(_ListDataReader[1])));
  10.  
  11.             }
  12.             myConnection.Close();
  13.             return myList;
  14.         }
  15.  
then I pass that back and I would like to ad this to the combobox now.

Expand|Select|Wrap|Line Numbers
  1.  loadPackages.ForEach(delegate(DBHelperDescValue dbhDV)
  2.            {
  3.                cboPackages.Items.Add(dbhDV.ItemDescription);
  4.                cboPackages.ValueMember = dbhDV.ItemValue.ToString();
  5.            });
  6.  
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.
Jan 17 '09 #5
mldisibio
190 Expert 100+
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.
Expand|Select|Wrap|Line Numbers
  1. cboPackages.ValueMember = "ItemValue";
  2.  loadPackages.ForEach(delegate(DBHelperDescValue dbhDV)
  3.            {cboPackages.Items.Add(dbhDV);});
  4.  
...using your syntax to illustrate...but this still will not work correctly.

Apparently you can only set ValueMember and DisplayMember if you actually bind a source collection to the ListBox.
Expand|Select|Wrap|Line Numbers
  1. cboPackages.DataSource = loadPackages; // (the List, I assume)
  2. cboPackages.ValueMember = "ItemValue";
  3. 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.
Jan 18 '09 #6
DragonLord
122 100+
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.
Jan 18 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Supa Hoopsa | last post by:
I have a databound combobox within a datagrid. I have set the DisplayMember and ValueMember. BUT, how do I capture the Value (SelectedValue) when the user changes the selection?
5
by: Steve | last post by:
I have an unbound combobox in the form header of a continuous form. The selection in the combobox sets the where clause in a querydef which determines QryPFrmInventoryManagement. The following code...
3
by: zfeld | last post by:
How do I add objects to a comboBox? What I need is something similar to what there was in MFC as MyObj obj; ComboBox cb; int index = cb.Add(obj.name); cb.AddItemData(&obj, index); Which...
9
by: Scott Johnson | last post by:
Hi! I have 2 items that I need to show in a ComboBox in VB.NET (CF) called ExpenseCode and Expense Description. I only want to show the user the ExpenseDescription in the dropdown ComboBox but...
4
by: Keith | last post by:
Hello - this started out as a minor annoyance - and now is starting to bother me more and more - I'm hoping someone can help me. I would like to have a combobox display - NOT initially be blank...
6
by: Sakharam Phapale | last post by:
Hi All, How to fill one ComboBox from other ComboBox control? 1) Only setting the reference does the trick but doesn't show items in control. If you see in immediate window, it shows...
4
by: c_shah | last post by:
I am a beginner and learning VB.net There are two wasy to bind a combobox or a listbox First approach is to assign a datasource and displaymember Second approach is to iterate through datarow...
1
by: Gian Paolo | last post by:
hi all i'm looking for a way to add 2 items in a combobox in the same line and hide one. i'm working on the code above but it returns me only the last value i entered and i do not know why.... ...
0
by: Frnak McKenney | last post by:
Can I use a bound ComboBox for both browsing and editing? I'm working on a small, standalone database application using Visual C#.NET 2003 and an Access data file. In order to keep the number...
8
by: =?Utf-8?B?RyBIdXN0aXM=?= | last post by:
This is the 2nd time posting so sorry for duplications. I am using VB.NT 2005 & a standard Combobox. I've been wracking my brain over this problem for a over a month & cannot seem to find a way to...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.