如何使用数据库中的数据填充下拉菜单?

时间:2011-09-08 11:40:23

标签: asp.net database combobox datasource

我继续收到此错误消息.InvalidCastException未被用户处理,无法将“System.Int32”类型的对象强制转换为“System.String”类型。 我被告知血型的视图数据值不正确。只是想弄清楚如何确定价值。 我是asp.net的新手,因此目前不太了解。

  <select name="bloodtype">
   <% List<Hospital.bloodtype> bloodtypeList = (List <Hospital.bloodtype>) ViewData["bloodtypeList"];
       foreach (Hospital.bloodtype st in bloodtypeList)

       { 
    %>  
       <option value="="<%= st.bloodcode%>"><% *if (st.bloodcode==(String) ViewData["bloodtype"])* Response.Write("Selected"); %><% Response.Write(st.meaning);%>></option> 
    <% } %> 
      <option value="0" <% if ((Int32) ViewData["bloodtype"]==0) Response.Write("Selected");%>>
      </option>



    public void HospitalInit()
    {

        hospitalSQLEntities db = new hospitalSQLEntities();
        ViewData["bloodtypeList"] = db.bloodtypes.ToList();
        ViewData["patientid"] = "";
        ViewData["patientname"] = "";
        ViewData["bloodtype"] = 0;
        ViewData["junk"] = "";
        ViewData["spam"] = "";
        ViewData["comments"] = "";
        ViewData["formmessage"] = "";
    }



    public ObjectSet<bloodtype> bloodtypes
    {
        get

        {
            if ((_bloodtypes == null))
            {
                _bloodtypes = base.CreateObjectSet<bloodtype>("bloodtypes");
            }
            return _bloodtypes;
        }
    }

2 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是在代码后面定义血型类型列表,如:

private List<bloodtype> _bloodtypes = new list<bloodtype>(); 

接下来,您可以使用放置在页面上的ASP.NET组合框控件,并将指定列表的数据绑定(也在后面的代码中),如下所示:

public void PageLoad(){    
    _bloodtypes = GetBloodTypes();
    myCombobox.DataSource = _bloodtypes;
    myCombobox.DataBind();
}

private IList<bloodtype> GetBloodTypes(){
    // Get some bloodtypes
    return new List<bloodtype>();
}

当然,在数据绑定之前,您需要填写列表(如上所示)。

答案 1 :(得分:0)

而不是使用转换

Convert.ToInt32(计算机[ “血型”])

相关问题