Dropdownlist in asp.net

Posted by Sheeba under ASP.NET on 4/1/2011 | Points: 10 | Views : 4779 | Status : [Member] | Replies : 5
Hi


what is diff b/w
ddlItemName.Items.Add(new ListItem("SELECT","0")); ,
ddlItemName.Items.Add("SELECT"); and
ddlItemName.Items.Insert(0, new ListItem("SELECT", "0"));

if i gave like this ddlItemName.Items.Insert(0, new ListItem("SELECT", "3")); means nothing happened rather than this i have to use like this means
ddlItemName.Items.Insert(3, new ListItem("SELECT", "0")); means error came....

explain me plz
.

Thnaks




Responses

Posted by: SheoNarayan on: 4/1/2011 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Hi Sheeba,

Add method adds the new item to the dropdownlist (or listbox) at the end of it and Insert method let you specify the index where you want to insert the new item.

ddlItemName.Items.Insert(3, new ListItem("SELECT", "0"))

Above code should add "SELECT" item at the 4th position as it is 0 based index.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Sheeba, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Sheeba on: 4/1/2011 [Member] Starter | Points: 25

Up
0
Down
Hi SheoNarayan

ddlItemName.Items.Insert(3, new ListItem("SELECT", "0"))

I have tried like this but it shows these issue

Error Occured:!Insertion index was out of range. Must be non-negative and less than or equal to size. Parameter name: index.

Thanks

Sheeba, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: T.saravanan on: 4/1/2011 [Member] [MVP] Silver | Points: 25

Up
0
Down
Hi Sheeba,

I think your dropdownlist count less than 4 then only its shown an error.
Try this...If you insert the postion at '4'
if(ddlItemName.Items.Count >=4)

{
ddlItemName.Items.Insert(3, new ListItem("SELECT", "0"))
}



Thanks,
T.Saravanan

Sheeba, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: SheoNarayan on: 4/1/2011 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
Ya, Saravanan is correct. Make sure that the index you are mentioning is within the max number of items in the DropDownList.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com

Sheeba, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Karthikanbarasan on: 4/3/2011 [Member] [Moderator] [Microsoft_MVP] [MVP] Silver | Points: 25

Up
0
Down
Hi,

As sheo and saravanan mentioned the problem might be bcoz of the count... Please check that... Also look at the below links to get clear idea on how the drop down list works out...

http://www.w3schools.com/aspnet/control_dropdownlist.asp
http://www.codersource.net/asp-net/asp-net-articles/dropdownlist-in-asp-net.aspx

Thanks
Karthik
www.f5Debug.net

Sheeba, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response