Click here to Skip to main content
15,911,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Object reference not set to an instance of an object.
I have got error when i click on data in listbox. I just want to get the selected items from the listbox and fill it to my textbox.
How to solve the same
Here is my code

VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    binddata()
End Sub

Public Sub binddata()
    Dim str As String
    Dim con As SqlConnection = New SqlConnection("Data Source=ML0003135586;Initial Catalog=TestSQL;Integrated Security=True")
    con.Open()
    str = "Select distinct [title] from [tblForums]"
    Dim command As SqlCommand = New SqlCommand(str, con)
    ListBox1.DataSource = command.ExecuteReader
    ListBox1.DataTextField = "title"
    ListBox1.DataValueField = "title"
    ListBox1.DataBind()
    con.Close()
End Sub

Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    txttitle.Text = ListBox1.SelectedItem.ToString
End Sub


Thanks in advance
Posted
Updated 26-Jul-11 18:17pm
v3
Comments
Sergey Alexandrovich Kryukov 26-Jul-11 22:26pm    
Line of code where exception is thrown is not indicated.
--SA
shefeekcm 26-Jul-11 23:59pm    
debug the code and provide the line the exception comes
Tajuddin_HYD 27-Jul-11 0:22am    
the problem because of not using postback condition, actually his calling binddata() in page load

Typo at txttitle.Text?
 
Share this answer
 
HI,
use this in page load


VB
If Not IsPostBack Then
    binddata()
End If
 
Share this answer
 
Why do you use Server side event to get selected item in Textbox.
Use Javascript it will help you to improve the performance.

Here is example

<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
    function callME()
    {
        alert(document.getElementById("lst1").value);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ListBox runat="server" ID="lst1" onclick="return callME()">
        <asp:ListItem Text="a" Value="a1"></asp:ListItem>
        <asp:ListItem Text="b" Value="b1"></asp:ListItem>
    </asp:ListBox>
    </form>
</body>


Hope it helps
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900