DropDown数据源

时间:2014-03-18 14:21:23

标签: c# asp.net linq linq-to-sql

当我尝试将数据源提供给下拉列表时,它抛出异常,我不知道错误,控件无法找到文本和值字段,当我不给文本和值fileds时,值被绑定为'变量',可以为此抛光。

 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;
 }

2 个答案:

答案 0 :(得分:1)

使用属性

public string NAME {get; set;}

答案 1 :(得分:0)

NAME中的IDVariable转换为属性。 DataTextFieldDataValueField寻找属性而非字段,尽管它们的名称。

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