Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Visual Basic > VB.NET 1.0 > VB.NET 2002/2003 Basics
|
VB.NET 2002/2003 Basics For coders who are new to Visual Basic, working in .NET versions 2002 or 2003 (1.0 and 1.1).
Welcome to the p2p.wrox.com Forums.

You are currently viewing the VB.NET 2002/2003 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old December 31st, 2003, 05:10 PM
Authorized User
 
Join Date: Dec 2003
Posts: 49
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to DolphinBay
Default Object reference not set to an instance of an obje

Good afternoon and Happy New Year to all...

I have just started the process of learning ASP.NET, and along with it VB.NET. As a classic ASP programmer with only VBScript knowledge, I am at a loss for even the most basic of error messages. I am receiving the error "Object reference not set to an instance of an object." from the following line of code:

lblDB.Text = lstBox.SelectedItem.Value

I am trying a basic example of populating a list box with information from a MySQL DB Table. From that list I am selecting an item and having the value of that item populate a label control.

The remaining code is following. Thank you in advance for any and all help.

<%@ Page Language="VB" Debug="true" %>
<%@ import Namespace="ByteFX.Data.MySQLClient" %>
<script runat="server">

    Sub button_click (s As Object, e As EventArgs)
       lblDB.Text = lstBox.SelectedItem.Value
    End Sub

</script>
<html>
<head>
</head>
<body>
<%
        Dim MyConString As String = "DATA SOURCE=xxx.xxx.xxx.xxx; DATABASE=aspx; UID=xxx; PASSWORD=xxx"
        Dim MyConnection As New MySQLConnection(MyConString)
        Dim MyCommand As New MySQLCommand("SELECT id, FName, LName FROM test")
        myCommand.Connection = myConnection
        MyConnection.Open()
        Dim rs As MySQLDataReader
        rs = MyCommand.ExecuteReader()

          While rs.Read()
             Dim myListItem As New ListItem()
             myListItem.Value = rs("LName")
             myListItem.Text = (rs("LName") & " ," & rs("FName"))
             lstBox.Items.Add(myListItem)
          End While
        MyConnection.Close()
        rs.Close()
%>
    <form runat="server">
        <table height="350" width="500">
            <tbody>
                <tr>
                    <td valign="top" width="50%">
                        <p>
                            <asp:ListBox id="lstBox" runat="server"></asp:ListBox>
                        </p>
                        <p>
                            <asp:Button id="btnSubmit" OnClick = "button_click" runat="server" Text="Submit"></asp:Button>
                        </p>
                    </td>
                    <td>
                        <asp:Label id="lblDB" runat="server">Label</asp:Label></td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>


 
Old December 31st, 2003, 06:29 PM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

When you set up a data listing control (list box, drop down box, datagrid, datalist, etc) .net saves the items in ViewState. When you click on items in the control to select or change selection the browser posts back to the server. When the page is run in PostBack mode, .net reconstructs the controls (including all the items in the control) from the posted viewstate. Then it analyzes what is NOW selected to determine what changed. It raises the necessary events to reflect its findings.

In your page load you are adding items to the listbox every time the page loads. This is not necessary with .net (unlike classic ASP). I think what is happening is that you are actually population the listbox with a second set of the same items from the database. SelectedItem is probably getting messed up because of this.

First, I would suggest removing the one assignment operation from your button handler. If you do this, I think you'll see that the listbox will fill up with another set of the items from the database for each button click (with the page crashing). To fix this, you need to wrap the database read and list population code inside of "If Not IsPostback Then...End If".

Then try adding back in the label assignment button click method and take it from there.

Also, you should do some searching on databinding. In .net, data listing controls can be "databound" such that you don't need to loop thru your data to populate a control. You just provide the control with a datasource, then you DataBind() it. If you were to use the following code, you'll see what I'm talking about...

Dim MyConString As String = "DATA SOURCE=xxx.xxx.xxx.xxx; DATABASE=aspx; UID=xxx; PASSWORD=xxx"
Dim MyConnection As New MySQLConnection(MyConString)
Dim MyCommand As New MySQLCommand("SELECT LName, LName+', '+FName AS FullName FROM test")
myCommand.Connection = myConnection
MyConnection.Open()
<s>While rs.Read()
    Dim myListItem As New ListItem()
    myListItem.Value = rs("LName")
    myListItem.Text = (rs("LName") & " ," & rs("FName"))
    lstBox.Items.Add(myListItem)
End While</s>
myListItem.DataSource = MyCommand.ExecuteReader()
myListItem.DataTextField = "FullName"
myListItem.DataValueField = "LName"
myListItem.DataBind()
MyConnection.Close()
rs.Close()

Peter
------------------------------------------------------
Work smarter, not harder.
 
Old December 31st, 2003, 07:29 PM
Authorized User
 
Join Date: Dec 2003
Posts: 49
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to DolphinBay
Default

Peter,

Thank you very much for your expansive explanation. I will give what you said a try.

Happy New Year.

Eric

 
Old December 31st, 2003, 07:41 PM
Authorized User
 
Join Date: Dec 2003
Posts: 49
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to DolphinBay
Default

Peter,

I took your advice from your previous post but am afraid I am still receiving the error message "Object reference not set to an instance of an object". Any other ideas?

TIA,
Eric

 
Old January 1st, 2004, 09:57 AM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

The SelectedItem property of a listbox will only be set to something if you have something selected it the listbox. If you have nothing selected when you press the button, SelectedItem will be Nothing. You need to check for this:

Sub button_click (s As Object, e As EventArgs)
    If Not lstBox.SelectedItem Is Nothing Then
        lblDB.Text = lstBox.SelectedItem.Value
    End If
End Sub

I don't recall off hand what happens if the listbox allows multiple selected items. In most cases, I deal with these in a different way.

If that still doesn't work, then it would seem that another object on that line of code is not set. The only other thing there is the label control. Break down the components of the code till you find the object that isn't set to an instance.

Peter
------------------------------------------------------
Work smarter, not harder.
 
Old June 27th, 2004, 11:35 AM
Registered User
 
Join Date: Jun 2004
Posts: 7
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I get object reference not set to an instance of an object when I define the "dgrdCourses" which is the datagrid which I will use in the HTML. My basic problem is that sometimes, as in this case, the code-behind does not have compatibility with the page.
For instance, the Datagrid here is member of the html but I have to define it in the VB part.

any suggestions for any of these problems??? pleaseeeeeeeeeeeeeee

        Dim dstCourses As DataSet
        Dim dadCourses As SqlDataAdapter
        Dim conn As SqlConnection
        Dim cmd As SqlCommand
        Dim dgrdCourses As DataGrid


        ' Create the DataSet
        dstCourses = New DataSet
        conn = New SqlConnection("server=e511;Integrated Security=SSPI;database=dissertation;")
        dadCourses = New SqlDataAdapter("Select * From Course", conn)
        dadCourses.Fill(dstCourses)

        ' Bind dataset to DataGrid
        dgrdCourses.DataSource = dstCourses<---------------
        dgrdCourses.DataBind()

"html part"
<asp:DataGrid id="dgrdCourses" runat="server"></asp:DataGrid>


 
Old June 28th, 2004, 03:14 AM
Friend of Wrox
 
Join Date: Jul 2003
Posts: 142
Thanks: 0
Thanked 2 Times in 2 Posts
Default

The problem here is that you've just declared a datagrid object, you've not actually instantiated it. i.e. you've done

 Dim dg As Datagrid

Whereas you needed to do

 Dim dg As New Datagrid

OR

 Dim dg As Datagrid = New Datagrid

I'm not 100% sure whether this will work, as you may have to pass arguments into the constructor for the datagrid, furthermore I'd say that you will face problems because you are trying to create a control rather than just an object variable when you create a datagrid. Your best bet is to draw a datagrid on your page/form and let Visual Studio take care of the coding for you, unless you don't want to display the datagrid at startup. In the latter instance, I'd still suggest using visual studio to get your datagrid looking and acting how you want, then just cut and paste the code.

Let me know how you get on.

Oh, btw, you'd be best off starting a new thread rather than replying to a six month old one - just looked a bit odd!

Jaucourt






Similar Threads
Thread Thread Starter Forum Replies Last Post
Object reference not set to an instance of an obje GS C# 2005 3 May 21st, 2007 10:11 AM
Object reference not set to an instance of an obje rturner003 ASP.NET 2.0 Professional 0 December 26th, 2006 08:30 PM
Object reference not set to an instance of an obje williadn General .NET 0 January 18th, 2005 05:39 PM
Object reference not set to an instance of an obje bekim Classic ASP Basics 1 August 9th, 2004 01:25 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.