DropDown datasource

2019-09-05 12:56发布

问题:

When I try to give datasource to dropdown it throws exception, I dono where am wrong,the control cant find the text and value field,when i dont give text and value fileds the value is binded as 'variables',can some one throw light for this.

 public void load()
{
    try
    {
        List<Variable> Div = new List<Variable>();
        List<Variable> Dep = new List<Variable>();
        using (DataContext db = new DataContext())
        {
            var cm = (from c in db.COMPANY_MASTERs
                      select c).FirstOrDefault();

            if (Convert.ToBoolean(cm.PLANT))
            {
                 Div = (from vp in db.PLANT
                           select new Variable()
                           {
                               ID = vp.PLANT_ID,
                               NAME = vp.PLANT_NAME
                           }).ToList();
            }
            if (Convert.ToBoolean(cm.ANIMAL))
            {
                Dep = (from vp in db.ANIMAL
                           select new Variable()
                           {
                               ID = vp.ANIMAL_ID,
                               NAME = vp.ANIMAL_NAME
                           }).ToList();
            }
            //this is what I am trying to do but cant,since the variables are nested                inside if.

              Div.AddRange(Dep);

            ddl1.DataTextField = "NAME";
            ddl1.DataValueField = "ID";
            ddl1.DataSource = Div.ToList();
            ddl1.DataBind();

        }
    }
    catch (Exception ex)
    {
    }
}
  public class Variable
 {
   public string NAME;
   public string ID;
 }

回答1:

use property

public string NAME {get; set;}


回答2:

Convert NAME and ID in Variable to properties. DataTextField and DataValueField look for properties rather than fields, in spite of their names.

public class Variable
{
    public string NAME { get; set; }
    public string ID { get; set; }
}