Re: How to iterate through a listbox by DilipM
DilipM
Wed Sep 21 23:22:01 CDT 2005
Hi Morten,
I am doign a multiselect and trying to loop through the selected values. I
think my biggest confsion was that ListBox.SelectedItems returns a
SelectedObjectCollection.
It is not at all intuitive that it is a bunch of DataRowView items.
Bart's mail earlier cleared that up.
"Morten Wennevik" wrote:
> Hi Dilip,
>
> There is no problem to read the USERNAME or any other field from the ListBox. Simply use the SelectedItem. When you fill a ListBox with data from a DataTable, the objects that are inserted are DataRowViews, one per row in the DataTable.
>
> DataRowView row = (DataRowView)listBox1.SelectedItem;
> string UserName = row["USERNAME"];
>
>
>
> On Wed, 21 Sep 2005 16:00:02 +0200, Dilip M"" <DilipM@discussions.microsoft.com> wrote:
>
> > HI Bart,
> >
> > Actually it was your post that I mentioned earlier. Thanks very much for
> > the quick reply!
> >
> > Yes, 'someListBox' and 'sendToAgent' are the same.
> >
> > I asumed the Tag value would appy to each item as I need a third field for
> > this. I guess I'll have to look for a workaround.
> >
> > I will try this out.
> >
> > Thanks again!
> >
> > "Bart Mermuys" wrote:
> >
> >> Hi,
> >>
> >> "Dilip M" <DilipM@discussions.microsoft.com> wrote in message
> >> news:1064EAE9-A98A-435C-9961-FC0351AD7549@microsoft.com...
> >> >I have the following code:
> >> > sendToAgent.DataSource = someDataSet.Tables[0];
> >> > someListBox.DisplayMember = "AGENTNAME";
> >> > someListBox.ValueMember = "AGENTID";
> >> > someListBox.Tag = "USERNAME";
> >>
> >> First you have "sendToAgent" then "someListBox", is it a typo ? Does the
> >> ListBox have a DataSource?
> >>
> >> ListBox.Text will give you the value of the DisplayMember field of selected
> >> row.
> >> ListBox.SelectedValue will give you the value of the ValueMember field of
> >> selected row.
> >> Tag doesn't apply to the items, it only allows you to associate any object
> >> with the ListBox itself.
> >>
> >> >
> >> > What I want to do is iterate through the selected values and retrieve the
> >> > displaymember, valuemember and Tag.
> >> >
> >> > I saw another post about extracting a DataRowView and using it but it
> >> > wouldn't work for me.
> >>
> >> Yes, but you don't show how you tried it or what went wrong, because if you
> >> bind to a DataTable and allow multiple selection then you need to get the
> >> values through a DataRowView.
> >>
> >> foreach ( DataRowView drv in someListBox.SelectedItems )
> >> {
> >> string agentName = (string) drv[someListBox.DisplayMember];
> >> int agentID = (int) drv[someListBox.ValueMember];
> >> string userName = (string) drv[(string)someListBox.Tag];
> >> // ....
> >> }
> >>
> >> hth,
> >> greetings
> >>
> >> >
> >> > I don't understand why this is so arcane.
> >> >
> >> > Any help would be MUCH MUCH appreciated!
> >>
> >>
> >>
> >
>
>
>
> --
> Happy coding!
> Morten Wennevik [C# MVP]
>