Solved

Get Value from VB.Net ListItems

Posted on 2011-03-20
11
444 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 

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
 
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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Convert Ctime to date time in textfile? 7 63
VS 2017 18 105
Amazon S3 Images with .Net 3 32
locate sql commands in C# visual studio Project 6 44
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

749 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