• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 454
  • Last Modified:

Get Value from VB.Net ListItems

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
jeffreyjseaman
Asked:
jeffreyjseaman
  • 5
  • 4
  • 2
1 Solution
 
nmarunCommented:
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
 
nmarunCommented:
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
 
Carl TawnSystems and Integration DeveloperCommented:
Are we talking about an ASP.Net ListBox or a WinForms ListBox?
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
jeffreyjseamanAuthor Commented:
@carl_tawn: ASP.Net Listbox.
0
 
jeffreyjseamanAuthor Commented:

@nmarun: This is the error I get back when I run your code.
Object reference not set to an instance of an object.
0
 
Carl TawnSystems and Integration DeveloperCommented:
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
 
jeffreyjseamanAuthor Commented:
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
 
Carl TawnSystems and Integration DeveloperCommented:
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
 
jeffreyjseamanAuthor Commented:
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
 
Carl TawnSystems and Integration DeveloperCommented:
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
 
jeffreyjseamanAuthor Commented:
@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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now