我想做的只是一个非常简单的选择/选择列表,其中包含来自 MySQL 数据库的值。
我试图在网上找到一个简单的解决方案(我是 C# 新手),我发现的一切都非常复杂。
我要做的就是生成<select><option..
etc 部分,以及我想要设置的所有属性和值。
这似乎应该非常非常容易。任何人都可以给我一些基本的说明,或者给我一个说明如何完成这个的教程吗?
目前,我正在使用MySqlCommand
andMySqlDataReader
类与数据库通信(用于另一个函数)。
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();
}
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";
通常,在列表/下拉列表中,您会获得 (a) 将被选择的值和 (b) 向用户呈现的值。第一个可能是一些主键,第二个可能是一些标签,对用户来说是不言自明的。
假设你有一张像食物这样的桌子
FoodValue | FoodLabel
---------------
00010 | Sausage
00020 | Eggs
00030 | Cheese
在您的 ASP.NET 视图中放置一个列表框,例如 listBox1,然后您可以在后面的代码中使用
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();
但请记住,这是一种快速而肮脏的方法。在生产代码中,您需要将表示层和数据层分开。使用数据源控件以更好的方式绑定您的数据。