DropDownList problem with SelectedIndex

  • Thread starter Thread starter Pat
  • Start date Start date
P

Pat

When selecting a DropDownlList to display some Data based on the
ddl.SelectedItem.Value
since a dropdownlist index starts from 0..
After selecting for example value1 and 2 which its ok but when you get back
to select 0
it gives an error "Object reference not set to an instance of an object."
So after selecting this
ddl.Items.Insert(0, "-- Select Company --")
i get the error
Any workarounds
 
Hi Pat,

Can you show some code snippets? Do you check for IsPostBack property
before population of your DropDownList? You might be rebuilding the DDL
every PostBack.

HTH,
 
thx for the reply.
In the database there is no CompanyID with the value "0" but i'm using the
SelectedItem.value to populate the Data 'm displaying
I have i.e
If Not Page.IsPostBack Then
GetCompany()
End If
And in the Sub:-
objDR = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
ddlcompany.DataSource = objDR
ddlcompany.DataValueField = "CompanyID"
ddlcompany.DataTextField = "CompanyName"
ddlcompany.DataBind()
' i get the error after first selecting the other optrions
and then select the "-- Select Company --"
ddlcompany.Items.Insert(0, "-- Select Company --")
 
Or i guess i should be able to use SQL to insert the "-- Select Company --"
Any ideas?
 
Change your code to this...

ddlcompany.Items.Insert(0, new ListItem("-- Select Company --", "0"))

The Insert method expects a ListItem object for its item parameter.

HTH,
 

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

Back
Top