dropdownlist

W

wei7028

i have create a webform that contain a dropdownlist that will show data
in my database. when i try to select a value in the dropdownlist and
display its value in a label but an error occur.
my code is as below:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

If Not IsPostBack Then
Dim myConn As SqlConnection = New
SqlConnection("Server=p800;" & _

"Database=SURVEY;UID=sa;PWD=")
Dim myCmd As SqlCommand = New SqlCommand("SELECT FORM_ID
FROM FORM", myConn)


myConn.Open()
Dim myReader As SqlDataReader = myCmd.ExecuteReader()

'Set up the data binding.
DropDownList1.DataSource = myReader
DropDownList1.DataTextField = "FORM_ID"
DropDownList1.DataValueField = "FORM_ID"
DropDownList1.DataBind()

'Close the connection.
myConn.Close()
myReader.Close()

'Add the item at the first position.
DropDownList1.Items.Insert(0, "<-- Select -->")
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click


Label2.Text = DropDownList1.SelectedItem.Value
Exit Sub
End Sub

the error msg:
Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.

Source Error:


Line 80:
Line 81:
Line 82: Label2.Text = DropDownList1.SelectedItem.Value
Line 83: Exit Sub
Line 84:

anyone who know the answer please tell me. thanks advance.
 
N

Nathan Sokalski

I am not entirely sure about this, but I think your problem is because of
the fact that you are trying to use an SqlDataReader as your DataSource. An
SqlDataReader is not good to use as a DataSource, DataReaders return one
piece of data at a time, a DataSource expects either an Array, Collection,
or DataSet. In your case I would recommend using a DataSet as your
DataSource. You may want to look at some examples of DataBinding as well.
 
P

Pat

Why don't you use "SelectIndexChanged" with your DropDownList and set your
DropDownlist to AutoPostBack.
That would work and hope that helps
Patrick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top