views:

359

answers:

1

Hi all I am triing to bind the data to a listbox from sql server then got the error "Value cannot be null.Parameter name: key"

ddlCountry = new Obout.ComboBox.ComboBox();
ddlCountry.Width = 200;
ddlCountry.Height = 200;
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Country";

sqlCommand = "SELECT [Country] FROM [tbl_LookupCountry] where [Country] IS NOT NULL";
SqlConnection sqlConCountry = new SqlConnection(connectString);
SqlCommand sqlCommCountry = new SqlCommand();
sqlCommCountry.Connection = sqlConCountry;
sqlCommCountry.CommandType = System.Data.CommandType.Text;
sqlCommCountry.CommandText = sqlCommand;
sqlCommCountry.CommandTimeout = 300;
sqlConCountry.Open();
reader = sqlCommCountry.ExecuteReader();
ddlCountry.DataSource = reader;
ddlCountry.DataBind();
sqlConCountry.Close();

Does anyone meet this problem before?

A: 

Ideally you should return the columns similar to "Id" and the "Name" of the country. The Id would be the value for the dropdown and the Name would be the text which the user would see in the dropdown.

Make sure you have the DataTextField and DataValueField of the dropdownlist assigned the "Id" and "Name" columns respectively for teh above example.

EDIT :- Pretty odd though, If this still does not work, could you try setting the SelectedValue of the dropdown to null just before the databind?

The other option to try to move the databinding code out of the If(!IsPostBack). This is odd again.

ydobonmai
I have already assign that, I did not paste the code about dropdown
Yongwei Xing
@Yongwei, I just edited my answer.
ydobonmai
Yes I have the DataTextField and DataValueField of the dropdownlist assigned to the "Id" and "Name" columns respectively for above example.
Yongwei Xing
Which line throws the error? Also, just for a question, Are you returning "Id" in the query and you have "Id" assigned to the ""DataKeyField" attribute of the dropdownlist?
ydobonmai
@ Ashish Gupta, I have update the post he error is threw at ddlCountry.DataBind(); The data is already read from sql
Yongwei Xing
Yongwei, could you try my edited answer once?
ydobonmai
@Ashish Gupta, I have found the reason, the reason is the order of the code, thank you for your helping.
Yongwei Xing