Link to home
Start Free TrialLog in
Avatar of Salah a a a Al Jasem
Salah a a a Al JasemFlag for Kuwait

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of Obadiah Christopher
Obadiah Christopher
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Salah a a a Al Jasem

ASKER

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
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The answer was what I am looking for