Reputation: 147
I have created a helper function to Bind Drop down list in asp.net. See my function:
public void BindDDL(string query, DropDownList DDL)
{
List<Issuetype> obj = new List<Issuetype>();
Issuetype iss = new Issuetype();
iss.DeptId = 1;
iss.Issue = "SSS";
iss.IssuetypeId = 4;
obj.Add(iss);
//BALissue Bl = new BALissue();
//List<Issuetype> objSource = null;
//objSource = Bl.Bind_issuetypes(query);
DDL.DataSource = obj;
DDL.DataValueField = Convert.ToString(obj[0]);
DDL.DataTextField = Convert.ToString(obj[1]);
DDL.DataBind();
}
In this way if i send the query name and Dropdownlist id to the function, drop down should be binded by the List of Issuetype entity, You can see the properties of Issuetype in code.
But however i am not able to Set the DataValueField and DataTextField correctly. Every time it is saying index out of range.
Upvotes: 1
Views: 6058
Reputation: 385
Actually there is no obj[1]
in your code because you have only one item in the obj
list, so at
DDL.DataTextField = Convert.ToString(obj[1]);
this line you will get the exception
Instead you can use
DDL.DataValueField = "Issue";
DDL.DataTextField = "IssuetypeId";
And to get property names use Reflection
using System.Reflection; // reflection namespace
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Console.WriteLine(propertyInfo.Name);
}
Upvotes: 1
Reputation: 76258
You need to specify the key and value fields. In your case, you're adding one item to list but trying to access the second (non-existent) item while trying to specify the value: Convert.ToString(obj[1])
.
What you probably want instead is this:
DDL.DataValueField = "IssuetypeId";
DDL.DataTextField = "Issue";
Upvotes: 1
Reputation: 18137
DataValueField
and DataTextField
should be names of the field in your collection, not values from the collection.
DDL.DataSource = obj;
DDL.DataValueField = "Issue"; //example choose what is needed
DDL.DataTextField = "IssuetypeId"; //example choose what is needed
DDL.DataBind();
The exception is thrown because in your collection you have 1 item, but you try to put second item(not exist) in DataTextField
. But this is not relevant if you fix your code.
Upvotes: 1