简体   繁体   中英

How do I create a picklist in ASP.NET/C#?

All I want to do is a very simple select/picklist with values from a MySQL database.

I'm trying to find a simple solution online (I'm new to C#) and everything I'm finding is very complicated.

All I want to do is generate the <select><option.. etc parts, with all the attributes and values that I want to set.

This seems like it should be very, very easy. Can anyone give me some basic instructions, or point me to a tutorial that shows how to accomplish this?

Currently, I am using MySqlCommand and MySqlDataReader for classes to talk to the database (for another function).

Create a class for the entity you want to display. Ex : If you want to show all states in the dropdown, create State class

public class State
{
  public int ID  { set;get;}
  public string Name { set;get;}
}

Now write a method in which you query the database and get the result to the DataReader, Iterate over the items and set the values a new object of our State class. Add each object to a list (of State class). So your method's return type will be a List of State class object.

public List<State> GetStates()
{
  List<State> stateList=new List<State>();

  // execute query, read from reader and add to the stateList
  // the below code is SqlServer DB specific.
  // you need to change the Connection,Command class for it to use with MySql.
   using (var con= new SqlConnection("replace your connection string"))
   {
      string qry="SELECT ID,NAME FROM STATES";
      var cmd= new SqlCommand(qry, objConnection);
      cmd.CommandType = CommandType.Text;           
      con.Open();
      using (var objReader = cmd.ExecuteReader())
      {
        if (objReader.HasRows)
        {
           while (objReader.Read())
           {
             var item=new State();
             item.ID=reader.GetInt32(reader.GetOrdinal("ID"));
             item.Name=reader.GetString(reader.GetOrdinal("Name"));

             stateList.Add(item);
           }
         }
       }
    }
    return stateList;
}

Now, have a DropDownList control in your page,

<asp:DropDownList id="states" runat="server" />

Now in the codebehind of this page, you can set the data for the dropdown( possibly in the Page_Load event)

if(!isPostBack)
{  
  states.DataSource=yourRepositary.GetStates();
  states.DataTextField="Name";
  states.DataValueField="ID";
  states.DataBind(); 
}

Generally, in a list/drop down you got (a) the value that will be selected and (b) its presentation to the user. The first one might be some primary key, the second might be some label which is self-explaining to the user.

Assuming you got a table FOOD like

FoodValue | FoodLabel
---------------
00010     | Sausage
00020     | Eggs
00030     | Cheese

Put a listbox in your ASP.NET view, eg listBox1, then you can read it in the code behind using

MySqlConnection con = new MySqlConnection("YOUR CONNECTION STRING");
MySqlCommand cmd = new MySqlCommand("SELECT FoodValue, FoodLabel FROM FOOD", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();

while(r.Read()) {
    listBox1.Items.Add(new ListItem(r["FoodLabel"], r["FoodValue"]);
}
con.Close();

But keep in mind this is a quick and dirty approach. In production code, you will need some separation of the presentation and data layer. Use the data source controls to bind your data in a better way.

I think what you searching for is something like a DropDownList , it accepts a DataSource , so you can use your already populated MySqlDataReader as it.

Something like this

MySqlDataReader dr = //the code to fill the MySqlDataReader
DropDownList1.DataSource = dr;

You can create the DropDownList in the design of your page.

To show the data you need to set then the values

DropDownList1.DataValueField = "DbField1";
DropDownList1.DataTextField = "DbField2";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM