Hi,
I want to display a text, getting from database, into a DropdownList using text property.

My Code::

SqlDataReader drd; 
if (drd.Read())
{
	drpcompname.Text  = drd.GetValue(0).ToString();

}

But It Display an error::

'drpcompname' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Please help me.

Thanks!
Pankaj Singh

Welcome Pankaj18,

Your source code must be surrounded with bb code tags. Read this How to use bb code tags?

Error message shows that a value you are assigned to the DropDownList control is not present inside the DropDownList's items.
Yes, the DropDownControl is empty. Isn't it?

Here, I am using bb code tags - See, how a source looks !!!

SqlDataReader drd; 
   .....
   if (drd.Read())
     {
        drpcompname..Items.Add(drd.GetValue(0).ToString());
     }

Welcome Pankaj18,

Your source code must be surrounded with bb code tags. Read this How to use bb code tags?

Error message shows that a value you are assigned to the DropDownList control is not present inside the DropDownList's items.
Yes, the DropDownControl is empty. Isn't it?

Here, I am using bb code tags - See, how a source looks !!!

SqlDataReader drd; 
   .....
   if (drd.Read())
     {
        drpcompname..Items.Add(drd.GetValue(0).ToString());
     }

I want to display at runtime not add

I want to display at runtime not add

drpcompname..Items.Add(drd.GetValue(0).ToString());
the above code add the items ,not display......

Does your dropdownlist contains items? If yes then use

drpcompname.SelectedValue=drd.GetValue(0).ToString();

Does your dropdownlist contains items? If yes then use

drpcompname.SelectedValue=drd.GetValue(0).ToString();

but it displays the same error::
drpclienttype' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

help me..

Pankaj Singh

First, fill the dropdownlist with values.

Thanks.
But it working when dropdownlist have some values, i have another case when i have no items in dropdownlist,it have only one item 'Select One', it display same error::
'drpcompname' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Thanks!

Pankaj Singh

Thanks,

Please, Mark this thread as Solved if you get solution.

If dropdownlist has no items (values) then you cannot assign a value for selection. This is the fact. Do not assign value if dropdown is empty.

You can handle this error

drpcompname.SelectedValue = drd.GetValue(0).ToString();

Replace the above statement with the following code

ListItem item = drpcompname.Items.FindByValue(drd.GetValue(0).ToString());
if (item != null)
        item.Selected = true;
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.