Find item from Dropdown, when dropdown binds with Objects like List<T>, Dictionary etc.
When your dropdown bind with List<Object> then you cannot find value from the dropdown list in simple way like we used to do in classic asp.net application
cboLanguage.SelectedIndex = cboLanguage.Items.IndexOf("10");
See in details below
Let's say you have one object called "Language"
public class Languages
{
public string Code { get; set; }
public string Name { get; set; }
}
And you are binding your Dropdown from this object List<Languages> like
List<Languages> lngs = new List<Languages>();
Languages lng = new Languages();
lng.Code = "10";
lng.Name = "Ritesh";
lngs.Add(lng);
----
---- etc.
Binding dropdown with this List of Objects
cboLanguage.ItemSource = Lngs;
Now if you want to find value on the dropdown and set the index then it will be different approach NOT simple like
Wrong: cboLanguage.SelectedIndex = cboLanguage.Items.IndexOf("10");
You have to select the complete object from the List<Languages> and then set the selected index for the dropdown
Right:
var item = lngs.Where(ip => ip.Code == "10").FirstOrDefault();
if (item != null)
{
cboLanguage.SelectedIndex = cboLanguage.Items.IndexOf(item);
}
In this way you can set default value for dropdown box.
No comments:
Post a Comment