borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder

AndreaVB Home | News Home | Forum Home | Downloads | Register | Search | PM | Profile

Previous Topic (Accessing and Manipulating XML Data in Microsoft .NET Framework)Next Topic (Upload Friendly (Multiple File Upload Applet)) New Topic Post Reply
AndreaVB OnLine : Articles and tutorials : Have your Own ItemData in .NET ComboBox
Poster Resource
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Have your Own ItemData in .NET ComboBox

If you are like me, you would have relied on the Combobox's .ItemData property in VB.OLD for any of your lookup fields in a database app. Recently I was working on a project in .NET in a situation where I would normally have used the .ItemData property to get additional info on my list items.

I was disappointed in finding out that .NET's combobox doesn't support the .ItemData property. Not wanting to change the design of my application (since I am still learning .NET) I tried to come up with a way to have metadata about my list item.

I considered many things , some of which are totally brain-dead - like maintaining a form level collection indexed by the combobox item text and the data being the numeric index for the entry.

I also thought of making my own combobox with itemdata and while following this route, I noticed in the documentation that the .Add method for the combobox takes an object parameter. Reading between the lines reveals that everything in .NET inherits from System.Object and displaying it as text implicitly calls its .ToString() method whch by default returns its type.

When I realised this, I tried creating a structure with all the fields my lookup enty had in the database and tried adding it to the combobox and it worked. Which is nice. Following is some simple code showing how to implement this in both VB.NET and C# to show how to use this strategy to store details about Account Types. To keep it simple, we will store only the typeID, the Typename and the interest rate.

C#
//code for the stucture here
private struct AccountType
{
public int AccTypeID;
public string AccountName;
public double InterestRate;

public AccountType (int _AccTypeID, string _AccountName, double _InterestRate)
{
AccTypeID = _AccTypeID;
AccountName = _AccountName;
InterestRate = _InterestRate;
}

public override string ToString()
{
return this.AccountName;
}
}


this is how you load it into the combo box and read it when the user clicks on one of them.

private void Form1_Load(object sender, System.EventArgs e)
{
comboBox1.Items.Add(new AccountType(23, "Fabulous Fadz Super Account", .9));
comboBox1.Items.Add(new AccountType(51, "A silly account that doesn't pay", .01));
comboBox1.Items.Add(new AccountType(84, "Yet another silly account", .02));
MessageBox.Show("The items are now loaded");
this.Text = "Select The Different Items and Watch";
}

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
//show the data in the relevant fields
AccountType acc = (AccountType)comboBox1.SelectedItem;
textBox1.Text = acc.AccTypeID.ToString();
textBox2.Text = acc.AccountName;
textBox3.Text = ((int)(acc.InterestRate * 100)).ToString() + " %";
}


VB.NET
This is the code for the structure.
Private Structure AccountType
    Dim TypeID As Integer
    Dim AccountTypeName As String
    Dim InterestRate As Single

    Public Sub New(ByVal _TypeID As Integer, ByVal _AccountTypeName As String, ByVal _InterestRate As Single)
        'store these values
        TypeID = _TypeID
        AccountTypeName = _AccountTypeName
        InterestRate = _InterestRate
    End Sub

    Public Overrides Function ToString() As String
        Return Me.AccountTypeName
    End Function
End Structure


And the code to put this in the combobox and translate it when the user selects an item from the list.
Private Sub frmDemo_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
    'for the purposes of this demo I am hard coding the entries
    With cboAccounts
       .Items.Add(New AccountType(23, "Fabulous Fadz Super Account", 0.9))
       .Items.Add(New AccountType(12, "Not so fabulous dull account", 0.02))
       .Items.Add(New AccountType(84, "Yet another silly account", 0.01))
    End With
    MessageBox.Show("The data is now loaded")
    Me.Text = "Select different entries and watch"
End Sub

Private Sub cboAccounts_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboAccounts.SelectedIndexChanged
    'in this case simply put the data up into the available fields
    Dim acc As AccountType = CType(cboAccounts.SelectedItem, AccountType)
    txtID.Text = acc.TypeID
    txtAccName.Text = acc.AccountTypeName
    txtInterest.Text = (acc.InterestRate * 100).ToString & " %"
End Sub


I will develop the idea further or ditch it if I find a more efficient way. Just thouht I would share it with anyone who needed it. Feel free to ask any questions or make comments.

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer

03-01-2004 at 12:16 AM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
computerg33k
Level: Guest

icon Re: Have your Own ItemData in .NET ComboBox

Since you were on the topic of combo boxes, I've been trying to create a combobox where I could have the format as last_nm, first_nm.  I am pulling from a SQL database, and have had no success so furth.  Any suggestions?  BTW--last_nm is in a seperate column from first_nm but they're in the same table. :

[Edited by admin on 27-05-2004 at 01:08 PM GMT]

25-05-2004 at 04:07 PM
| Add Comment
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Have your Own ItemData in .NET ComboBox

Hi Dana, I don't know if I have fully understood what you want to do but let me try to help.

What I do with my classes is to make them correspond to a table or set of tables in the database; for instance, if there is a departments table in the database I have a department class in my application which contains all the code to read the departments from the db and to modify and delete them.

There are a lot of shared methods/static on these classes to get the Department such as:


//C#
public static Department GetDepartment(int deptID)
{
  SqlConnection con = new SqlConnection(Common.GetConnectionString());
  ...
  return dept;
}

'VB
Public Shared Function GetDepartment(Byval deptID As Integer) As Department
  Dim con As New SqlConnection(CommonLogic.GetConnetionString())
...
  Return dept
End Function


This will return all the info I need from on the department and I can access everything about it without going back to the db. For display purposes I then override the ToString function to make it display whatever I want. So if I want to display the department in the combo box as DeptName, DeptHead I would override the ToString method as such:


//C#
public override string ToString()
{
  return this.DepartmentName + ", " + this.DepartmentHead.FullName;
  //the above assumes that DepartmentHead is a property of the class person
}

'VB.NET
Public Overrides Function ToString() As String
  Return Me.DepartmentName & ", " & Me.DepartmentHead.FullName
End Function


When I add a department to the combobox it would display the IT department as such


quote:
Information Technology, fabulous


What you could do about your data is override the ToString method. I am guessing that you data is referring to a person (last name, first name):


//C#
Class person
{
  public string FirstName;
  public string LastName;
  
  public string FullName()
  {
    return FirstName + " " + LastName;
  }

  public string FullName(bool reverse)
  {
    if(reverse)
      return LastName + ", " + FirstName;
    else
      return FullName();
  }

  public override string ToString()
  {
    return this.FullName(true);
  }
}

'VB.NET
Public Class Person
  Public FirstName as String
  Public Lastname as String

  Public Function FullName() As String
    Return FirstName & " " & LastName
  End Function

  Public Function FullName(ByVal reverse As Boolean) As String
    If reverse Then
      Return LastName & ", " & FirstName
    Else
      Return Me.FullName()
    End If
  End Function

  Public Overrides Function ToString() As String
    Return Me.FullName(True)
  End Function
End Class


I hope this helps. If not let me know with more details and I will help you. Happy coding

[Edited by fabulous on 05-06-2004 at 04:41 PM GMT]

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer
27-05-2004 at 09:09 AM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
GeoffS
Level: VB Lord


Registered: 29-09-2004
Posts: 536
icon Re: Have your Own ItemData in .NET ComboBox

fabulous - indeed you are
I like this idea 'cos I first started with vba + Access where you could have as many "columns" of data in the combo list as you wanted. VB6 allowed the .ItemData which, as you say, was very necessary for retrieving further information on the selected item, but you had to either cache the info. or make a return to the database to get it. Now I can use the same style as I did with the Access combo and have the extra details readily to hand. GREAT.
HOWEVER, as far as .ItemData is concerned, if you have bound the control to a Dataset then you can retrieve the record by using ComboBox.ValueMember in VB.NET or ComboBox.DataValueField in ASP.NET


____________________________
multi-tasking - the ability to hang more than one app. at the same time.

12-10-2004 at 03:55 PM
View Profile Send Email to User Show All Posts | Add Comment
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Have your Own ItemData in .NET ComboBox

Hi Geoff, thanks for you kind words.

I'm sorry I took an eternity to respond, I have had lots on my plate, good stuff and bad stuff and was away from the internet for a large part of the time.

You rightly point out the ValueMember of the combo box. At the time I wrote this article however, I didn't know this. And I needed a way to use some of the application logic in the class. In VB6, I would use the .ItemData to create an instance of a class that I needed. Now, with datasets and all these other data related ADO.NET classes, I needed to use the Class straight away without creating it again.

This is when I developed this method and can now use the object as soon as the user selects it. Thanks for the kind words again, and feel free to make any further comments.

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer

04-01-2005 at 04:29 PM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
erhm
Level: Trainee

Registered: 23-02-2005
Posts: 1
icon Re: Have your Own ItemData in .NET ComboBox

Ditto.  Fabulous baby!  

I came very close in my own efforts.  But used the "Shadows" keyword rather than "Overrides".  

I've been coding for 20+ years in any number of languages.  I'm finding the transition to .NET particulalry painful.  Thanks!

23-02-2005 at 04:15 PM
View Profile Send Email to User Show All Posts | Add Comment
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Have your Own ItemData in .NET ComboBox

erhm, thanx for the kind words.

I never saw your reply until just a few minutes ago. Since leaving my job I cannot get regulare access to the internet (except from internet cafes) and cannot seem to get a phone line installed at home without bribing someone (which I won't do).

Thanks again and glad you liked the article.

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer

29-04-2005 at 03:31 PM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
SBendBuckeye
Level: Trainee

Registered: 03-06-2005
Posts: 1
icon Re: Have your Own ItemData in .NET ComboBox

Very nice. I have been looking for a way to override the Items.Add for a custom combobox. This may help that process, but the problem I am having is trapping the standard Items.Add("One Value") which goes directly to MyBase.Item.Add.

Because the Items collection is a ComboBox.ObjectCollection I don't know how to override it. Does this pertain to that? Sorry for my lack of knowledge. I am coding in VB.Net. Thanks!

____________________________
Have a great day!
j2associates_NO_SPAM_@yahoo.com

03-06-2005 at 09:57 PM
View Profile Send Email to User Show All Posts | Add Comment
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Have your Own ItemData in .NET ComboBox

Sorry I took a long time to respond to this one. I have been away from the intenet for a while and only get to check my reply notifications a little bit. This one slipped my attention until just now.

For you to override the Items.Add method, you will have to write a class of your own that inherits from ComboBox.ObjectCollection and then override the add method from in there. I have not had to do this before, so I regret to say that you're on your own .

However, if you encounter problems while going that route, you can post here or in the main forum and you will get your problem solved. Happy coding

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer

11-07-2005 at 05:04 PM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
sergioseva
Level: Trainee

Registered: 28-03-2006
Posts: 1
icon Re: Have your Own ItemData in .NET ComboBox

I maked a solution in the same way that you, but i have a problem when i call the indexof method.
I'm explain using your example,
When i call cboAccounts.items.indexOf(new AccountType(12, "not so fabulous dull account", 0.02))
Should return 1 but return -1, then I try overriding the equals method of AccountType like this

public overrides function equals(byval obj as object) as boolean
        if (obj.gettype is me.gettype) then
            equals = (me.typeid  = (AccountType)obj.typeid)
        else
            equals = false
        end if

but it doesn´t work, the method doesn´t find the element
Do You know if is there a way to find the element without need to compare strings?

28-03-2006 at 08:30 PM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
fabulous
Level: VB Guru


Registered: 03-08-2002
Posts: 439
icon Re: Have your Own ItemData in .NET ComboBox

quote:
When i call cboAccounts.items.indexOf(new AccountType(12, "not so fabulous dull account", 0.02))



What IndexOf does is look for the instance you gave it and tell you where it is. In this case, you are creating a new instance and searching for that and because of that reason, it cannot be found.

What you will need to do is to store the object somewhere first, and then later when you want it, you will search for the item as in...

'assuming acc was declared
acc = New AccountType(12, "not so fabulous dull account", 0.02))
cboAccounts.items.IndexOf(acc)


Hope this helps

____________________________
My boss is a Jewish Carpenter (Jesus Christ)


Brain Bench Certified VB.NET Developer
08-04-2006 at 05:01 AM
View Profile Send Email to User Show All Posts Visit Homepage | Add Comment
deepsdeeps
Level: Trainee

Registered: 11-05-2006
Posts: 1
icon Re: Have your Own ItemData in .NET ComboBox

quote:
fabulous wrote:
quote:
When i call cboAccounts.items.indexOf(new AccountType(12, "not so fabulous dull account", 0.02))



What IndexOf does is look for the instance you gave it and tell you where it is. In this case, you are creating a new instance and searching for that and because of that reason, it cannot be found.

What you will need to do is to store the object somewhere first, and then later when you want it, you will search for the item as in...

'assuming acc was declared
acc = New AccountType(12, "not so fabulous dull account", 0.02))
cboAccounts.items.IndexOf(acc)


Hope this helps




i tried the above code but it doesnt work pls mail me if any solution is there for takeing the index of a particular Itemdata








[Edited by deepsdeeps on 11-05-2006 at 11:35 AM GMT]

[Edited by deepsdeeps on 11-05-2006 at 11:36 AM GMT]
11-05-2006 at 11:34 AM
View Profile Send Email to User Show All Posts | Add Comment
AndreaVB OnLine : Articles and tutorials : Have your Own ItemData in .NET ComboBox
Previous Topic (Accessing and Manipulating XML Data in Microsoft .NET Framework)Next Topic (Upload Friendly (Multiple File Upload Applet))New Topic Post Reply
Surf To:


Not Logged In? Username: Password: Lost your password?
Partners: Download Actual Software | Free Software Download
borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder