Solved

Get Value from VB.Net ListItems

Posted on 2011-03-20
11
440 Views
Last Modified: 2012-05-11
Hello,

I have a hopefully simple issue that I can't figure out. I have a list of items that I load from a stored procedure into the list box. When I click on a value I can't get the value.

If I were to populate the listbox manually it works. I've populated my issues.

Thanks
--This Code is used to load the ListBox
Public Sub LoadListBox(ByVal lstListBox As ListBox, ByVal strType As String)
        ' loads a stored proc into a data table 

        'if Commercial we don't want to load the Factory ListBox
        'If Not bolFactory And lstListBox.ID = "lstFactory" Then Exit Sub

        lstListBox.Items.Clear()


        SqlConn.Open()

        Dim SqlCmd As SqlCommand = New SqlCommand()
        SqlCmd.Connection = SqlConn
        SqlCmd.CommandText = "Ringgold_Security_Users"
        SqlCmd.CommandType = CommandType.StoredProcedure

        'SqlCmd.Parameters.AddWithValue("UserID", CInt(Me.lblUserID.Text))

        'SqlCmd.Parameters.AddWithValue("Type", strType)

        ' Create a DataReader
        Dim theReader As SqlDataReader
        theReader = SqlCmd.ExecuteReader

        'Iterate through the results
        Dim intTmp As Integer
        intTmp = 0


        While theReader.Read()
            lstListBox.Items.Add(theReader(0).ToString)
            lstListBox.Items(intTmp).Value = theReader(0).ToString
            'If UCase(theReader(1)) = "Y" Then lstListBox.Items(intTmp).Selected = True
            intTmp = intTmp + 1
        End While


        SqlCmd = Nothing
        theReader.Close()
        theReader = Nothing
        SqlConn.Close()

    End Sub

--This code here I use to get the value when I select the value on the ListBox.
Dim list As String = ListBox1.SelectedItem.Text

Nothing Works..

Open in new window

0
Comment
Question by:jeffreyjseaman
  • 5
  • 4
  • 2
11 Comments
 
LVL 27

Expert Comment

by:nmarun
ID: 35177800
You need to "listen" to the SelectedIndexChanged event. The below snippet worked for me.

Arun
<asp:ListBox ID="myList" runat="server" AutoPostBack="true" />
<asp:Label ID="myLabel" runat="server" />

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ListItem listItem = new ListItem("asdf", "1");
        myList.Items.Add(listItem);
        listItem = new ListItem("zxcv", "2");
        myList.Items.Add(listItem);
        listItem = new ListItem("qwer", "3");
        myList.Items.Add(listItem);
        myList.SelectedIndexChanged += myList_SelectedIndexChanged;
    }
}

void myList_SelectedIndexChanged(object sender, EventArgs e)
{
    myLabel.Text = string.Format("{0} - {1}", myList.SelectedItem.Text, myList.SelectedItem.Value);
}

Open in new window

0
 
LVL 27

Expert Comment

by:nmarun
ID: 35177805
Sorry, here's the vb.net version.

Arun
Protected Sub Page_Load(sender As Object, e As EventArgs)
	If Not IsPostBack Then
                ' adding some dummy data for the example
		Dim listItem As New ListItem("asdf", "1")
		myList.Items.Add(listItem)
		listItem = New ListItem("zxcv", "2")
		myList.Items.Add(listItem)
		listItem = New ListItem("qwer", "3")
		myList.Items.Add(listItem)
		AddHandler myList.SelectedIndexChanged, AddressOf myList_SelectedIndexChanged
	End If
End Sub

Private Sub myList_SelectedIndexChanged(sender As Object, e As EventArgs)
	myLabel.Text = String.Format("{0} - {1}", myList.SelectedItem.Text, myList.SelectedItem.Value)
End Sub

Open in new window

0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35178679
Are we talking about an ASP.Net ListBox or a WinForms ListBox?
0
 

Author Comment

by:jeffreyjseaman
ID: 35179744
@carl_tawn: ASP.Net Listbox.
0
 

Author Comment

by:jeffreyjseaman
ID: 35179747

@nmarun: This is the error I get back when I run your code.
Object reference not set to an instance of an object.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 35179855
I can only think that you are running the code to populate your listbox even on postback. The call to Clear() will drop all the items in the listbox and therefore also lose the context for the SelectedItem.
0
 

Author Comment

by:jeffreyjseaman
ID: 35179904
Ifnotpostback only is when I populate my listbox. I will load the first time. Select the value from the list and then the code will pick up a change and go to pick up that value. I don't have set to clear. It's odd cause I thought this would be easy.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35179946
It should be :)

The fact it isn't working would suggest something else is interfering with the listbox. Do you interact with it anywhere else, modify it from client code, etc?

Can you post the definition for your listbox?
0
 

Author Comment

by:jeffreyjseaman
ID: 35179990
No. I can send the entire code snippet if that will help. I on the trolley into work. I will have to post this evening.
Thx
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 35180040
That would be helpful. Especially if your listbox is sat inside an update panel or any other container.

There is certainly nothing wrong with what you appear to have at the moment, and it should be working fine. Therefore it is just a cse of taking a broader look at the make up of the page to see what else is affecting things.
0
 

Author Comment

by:jeffreyjseaman
ID: 35182547
@carl_Tawn:

I started to think maybe I didn't put the the If Not IsPostBack into my code. I wrote it at work real quick on my lunch break to test it that way. Boom do you know it works. So as I said sometimes the little things you leave out is the answer. Thanks for your help. You're getting the points.

 If Not IsPostBack Then
            LoadListBox(ListBox1, "string")

        End If
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Retain selection in datagridview 2 24
Visual Studio installation 5 39
Problem to ToolkitScriptManager 2 32
Hovering effect 9 30
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now