Binding Data text field and Data value field to asp:Dropdownlist

Total Post:29

C#  Dropdown 
 1341  View(s)
Rate this:

I have created a helper function to Bind Drop down list in 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;
        //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]);

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.

  1. Post:48

    Re: Binding Data text field and Data value field to asp:Dropdownlist

    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; 
            PropertyInfo[] propertyInfos;
            propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public | BindingFlags.Static);
            delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
            { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
                foreach (PropertyInfo propertyInfo in propertyInfos)

      Modified On Apr-06-2018 03:41:49 AM