• 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">
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>

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


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.
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"))


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

Open in new window

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