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

Can not get (Listbox.Selecteditem.Value)

Can not get (Listbox.Selecteditem.Value)
It gives error (Object reference not set to an instance of an object)

Here is aspx code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
    </div>
    </form>
</body>
</html>

Here is the code behind

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        ListBox1.Items.Clear()
        ListBox1.Items.Add(New ListItem("saljas", "123"))
    End Sub
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xxx As String
'(the error is on the following line "Object reference not set to an instance of an object.")
       xxx = ListBox1.SelectedItem.Value  
'( note that (ListBox1.items count) works fine)
    End Sub
End Class

Help is appreciated
0
saljas
Asked:
saljas
  • 2
  • 2
2 Solutions
 
Obadiah ChristopherCommented:
You need to add the check for IsPostback in ur page load event before you bind the listbox. here’s a c# example.

If(!Page.IsPostBack)
{
ListBox.Items.Add();
}

What is happening in your code is that the Listbox is being bound each time you click the button and you are losing the selecteditem value.
0
 
saljasAuthor Commented:
do you mean

(if the page is posted back then do not add to list)
        If Page.IsPostBack Then Exit Sub      
        ListBox1.Items.Add(New ListItem("salah", "123"))

Or

(if the page is posted back then add to list)
        If Page.IsPostBack Then        
            ListBox1.Items.Add(New ListItem("salah", "123"))
        End if
0
 
Obadiah ChristopherCommented:
If Not IsPostBack
            ListBox1.Items.Add(New ListItem("salah", "123"))
        End if 

Open in new window

0
 
saljasAuthor Commented:
The answer was what I am looking for
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

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

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