Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hallo, I need help in setting the selected index in the DropDownList when the page is opened from a different page, the problem is I don't know how to do this with the DropDownList in the GridView. Can anyone show me how to do this please?
Posted

Hi there...

At the page where your GridView and DropDownList in it exists....

... I suppose your GridView Id is gdvUser and DropDownList id is drpUser... put these line to set index... and you're binding only one record to the GridView...

C#
DropDownList drpL = (DropDownList) gdvUser.Rows[0].FindControl("drpUser");
drpL.SelectedIndex = 0; // I set 0 you can set it to any existing index


In above code, I supposed you're filling only one record so I targeted Row at position 0 in GridView. You can target any row as per your requirement. In case you want to set DropDownList index for all records in GridView, you can use for loop...

C#
for(int i=0;i<gdvUser.Rows.Count;i++)
{
   DropDownList drpL = (DropDownList) gdvUser.Rows[i].FindControl("drpUser");
   drpL.SelectedIndex = 0; // I set 0 you can set it to any existing index
}


Also you can find an Item of dropdown list using Text or Value properties of item.

Examples:

C#
DropDownList drpL = (DropDownList) gdvUser.Rows[0].FindControl("drpUser");
drpL.clearSelection();
drpL.Items.FindByText("SomeText").Selected = true;


C#
DropDownList drpL = (DropDownList) gdvUser.Rows[0].FindControl("drpUser");
drpL.clearSelection();
drpL.Items.FindByValue("SomeValue").Selected = true;


C#
DropDownList drpL = (DropDownList) gdvUser.Rows[0].FindControl("drpUser");
ListItem li = new ListItem("SomeText","SomeValue");
drpL.clearSelection();
drpL.Items[li].Selected = true;


Note: In above three examples it's important to clear the selection before programmatically selecting a new item, otherwise an error will be shown about no more than a ListItem can be selected at a time.

I hope you got the solution of your query. Good Luck! :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900