henna
henna

Reputation: 1

How can I populate the pull down menu using data from a database?

I keep on getting this error message.InvalidCastException was unhandled by the user, Unable to cast object of type 'System.Int32' to type 'System.String'. I've been told the view data value for bloodtype is not correct. Just trying to figure out how to determine the value. I'm new to asp.net therefore don't understand too much at the moment.

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

Upvotes: 0

Views: 201

Answers (2)

Christian
Christian

Reputation: 3972

Instead of casting use convert

Convert.ToInt32(ViewData["bloodtype"])

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

The best way to do this is to define a list of bloodtypes in your code behind like:

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

Next, you can use an ASP.NET combobox control that you place on your page and to which you databind the specified list (also in the code behind), like so:

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

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

Of course, before databinding, you need to fill the list (as seen above).

Upvotes: 1

Related Questions