Hey there

i have been trying to bind a table from database to a listbox. I know this can be done quite easily but i keep having an error with i cannot figure out why.

Whenever i declare selectedMain as linklist.selectedItem.value, it will alsways tell me "Object reference not set to an instance of an object"

Please help me? thanks in advance

<script language="VB" runat="Server">
'path where xml file will be created

Sub page_Load(Sender as Object, E as EventArgs)
Dim ConODBC As new OdbcConnection 
Dim cmdSelect as new OdbcCommand
Dim dsSet as new DataSet()
Dim dbApt as new OdbcDataAdapter
Dim dtrworks As OdbcDataReader

Dim connStr as String
connStr =""
ConODBC = New OdbcConnection(ConnStr)
conODBC.Open()

cmdSelect.Connection = ConODBC
cmdSelect.commandText = "select f_title, f_content from features_list"

dbApt.selectCommand = cmdSelect
dbApt.Fill(dsSet, "features_list")


'listbox-------------------------------------------------

Dim dtr as IDataReader = cmdSelect.executeReader()
linklist.DataSource = dtr

linklist.DataTextField = "f_title"
linklist.DataValueField = "f_title"
linklist.DataBind()

conODBC.Close

End Sub

'the upon click on the first listbox method__________________________

Sub linklist_SelectedIndexChanged(S as Object, E as EventArgs)
Dim ConODBC As new OdbcConnection 
Dim cmdSelect as new OdbcCommand
Dim dsSet as new DataSet()
Dim dbApt as new OdbcDataAdapter
Dim dtrworks As OdbcDataReader

Dim connStr as String
connStr =""
ConODBC = New OdbcConnection(ConnStr)
conODBC.Open()


Dim selectedMain

selectedMain=linklist.selectedItem

selectedMain = linklist.selectedItem.value

testing.text = string.format("the selected one in listbox is" & selectedMain)

conODBC.Close
end sub

</script>
<html>
<head>
</head>
<body>

<form id="form1" runat="server">
  <asp:ListBox BackColor="#CCCCCC" ID="linklist" Rows="5" runat="server" SelectionMode="single" AutoPostBack="true" OnSelectedIndexChanged="linklist_SelectedIndexChanged" target="_blank"/>
  <asp:label ID="testing" runat="server"></asp:label>
</form>

</body>

Recommended Answers

All 11 Replies

Umm yes. That error tells your exactly what you need to know!!

*sigh*:rolleyes::rolleyes:

You have not declared the selectedMain as anything. :cry: :cry:

It should be:
i.e. Example

Dim selectedMain As String
or
	Dim selectedMain As Integer

See here for a detailed tutorial.

Hope this helps

umm.. yea i have tried that but it doesnt work. But i have managed to solve it.

i'll try to look at the tutorial.

thanks alot

See I find that strange, because this error you are getting : Object reference not set to an instance of an object" is telling you that you have not set a declared Object to an Object type.

When you type DIm you are declaring an object in memory. You then state the key word as to associate that object with an Object Type. Just Dim'ing a variable with no type associated with it means you have declared an object of no type.

Glad you got it solved, care to share how you did it? Others may be interested.

See I find that strange, because this error you are getting : Object reference not set to an instance of an object" is telling you that you have not set a declared Object to an Object type.

When you type DIm you are declaring an object in memory. You then state the key word as to associate that object with an Object Type. Just Dim'ing a variable with no type associated with it means you have declared an object of no type.

Glad you got it solved, care to share how you did it? Others may be interested.

Paladine,
If you declare something like

Dim var1

.NET declares it as of type object.

When you associate the Object with a value Like "Just hi" which is a string like

var1 = "Just hi"

Then the datatype of var1 will be a String.

Similarly if you associate an Integer with the object var1,something like

var1= 1

then the type for the object var1 will become an integer.

Yes I know that, but it is not proper coding practice to declare a variable and not define a data type. Implied datatypes are dangerous ways of coding.

Saying that, it appears that this is a known bug:

Object Reference.....

I know YOU know that,
But I feel the problem must not be in the declaration of selectedMain datatype.

hm.. well, as Paladine has said, it may not be good coding practise to not indicate the type of the variable.

As i not too sure what it should be declared at, i leave it as it is.

Dim selectedMain
selectedMain = listbox.selectedValue.ToString

this may tell selectedMain that it suppose to be a string (?)

Ok, well I thought it was clear in the tutorial on listbox populating and retrieving data, but let me see if I can better explain it.

The DataValueField of the listbox control is the value/datatype of the field you assign as the primary key. Thus the SelectedItem.Value would be this primary key value, and datatype.

Now saying that, remember what the definition of a Primary Key is = a unqiue identifier. It is not good practice to have duplicate Primary Keys. So if your f_title field has duplicates think of the error potential when the user selects on of those duplicates from the listbox. The code will not know where item is being selected for certain.

so your code would be

Dim selectedMain As String ' Assuming f_title is a string or varchar() datatype
selectedMain = linklist.SelectedItem.Value

But I am guessing at the datatype of the f_title field.

Hope this clears things up for the Declaration issue... but I am wondering if you have completed this or not?


hm.. well, as Paladine has said, it may not be good coding practise to not indicate the type of the variable.

As i not too sure what it should be declared at, i leave it as it is.

Dim selectedMain
selectedMain = listbox.selectedValue.ToString

this may tell selectedMain that it suppose to be a string (?)

Just to give things a whirl, here is the code I have for a working example

Now I have used CodeBehind as opposed to script, and I have set the listbox to autopostback = true:

HTML Code:

WebForm1 	 		 		 		 		 		 	 		 			 			 		 	<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="ListboxTest.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
	<HEAD>
	    <title>WebForm1</title>
		<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
		    <asp:ListBox id="linklist" style="Z-INDEX: 101; LEFT: 224px; POSITION: absolute; TOP: 48px" runat="server"
		        Width="424px" Height="216px" AutoPostBack="True"></asp:ListBox>
		    <asp:Label id="lblSelection" style="Z-INDEX: 102; LEFT: 224px; POSITION: absolute; TOP: 328px"
		        runat="server" Width="432px" Height="40px"></asp:Label>
		</form>
	</body>
</HTML>

VB.NET CodeBehind Code:

Imports:

Imports System.Data
Imports System.Data.SqlClient

Page_Load and SelectedIndex_Change:

Const SQLCONN As String = "Network Library=DBMSSOCN;Data Source=192.168.0.100,1433;database=Northwind;User id=;Password=;"
	Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		If Not Page.IsPostBack Then
			LoadList()
			linklist.SelectedIndex = 0
		End If
	End Sub
	Private Sub LoadList()
		Dim strSQL As String = "SELECT ProductID, ProductName FROM Products"
		Dim connStr As SqlConnection = New SqlConnection(SQLCONN)
		Dim objCmd As New SqlCommand(strSQL, connStr)
		Dim objReader As SqlDataReader

		connStr.Open()
		objReader = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
		linklist.Items.Clear()

		'   SET Primary Key value for ListBox
		linklist.DataValueField = "ProductID"
		'   SET Display field for Listbox
		linklist.DataTextField = "ProductName"
		'   SET Datasource for Listbox
		linklist.DataSource = objReader
		linklist.DataBind()

		objReader.Close()

	End Sub
	Private Sub linklist_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles linklist.SelectedIndexChanged
		Dim MyConn As SqlConnection = New SqlConnection(SQLCONN)
		Dim myCmd As SqlCommand
		Dim objReader As SqlDataReader
		Dim strSQL As String = "SELECT ProductName FROM Products"
		strSQL &= " WHERE ProductID = " & linklist.SelectedValue
		Dim strItemSelected As String
		myCmd = New SqlCommand(strSQL, MyConn)

		MyConn.Open()

		objReader = myCmd.ExecuteReader(CommandBehavior.CloseConnection)
		Do While objReader.Read()
			strItemSelected = objReader.Item("ProductName")
		Loop
		lblSelection.Text = "The Item you have selected is : " & strItemSelected

	End Sub

I hope this helps you out, but I still think that bug is going to be your issue.

Happy Coding! :cool:

well, no i have not complete it yet. I got to work on other stuff before coming back to this. I was trying to understand the codes n all but i guess i need more time in understanding and implementing them.

thanks a lot! :)

Well if you need any help with explainations of why's and where's let us know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.