Switch语句查询MYSQL数据库

Switch语句查询MYSQL数据库

我试图建立一个程序,如果用户从下拉列表中选择了一些东西,那么根据选择的内容,将显示一个标签。
如:
从下拉列表中选择狗,标签将显示“狗是20英镑”
从下拉列表中选择猫,标签将显示“猫是15英镑”
我做得不对,已经做了好几个小时了,如果有什么帮助,我将不胜感激。
迄今为止的代码

DataSet ds = new DataSet();
MySqlConnection cs = new MySqlConnection(@"SERVER= 000.000.00.000;username=myusername;password=******; Initial Catalog = mydatabase");
MySqlDataAdapter da = new MySqlDataAdapter();

protected void Page_Load(object sender, EventArgs e)
{
   MySqlCommand cd = new MySqlCommand("SELECT * FROM pets", cs);
   cs.Open();
   MySqlDataReader ddl = cd.ExecuteReader();
   DdPetPist.DataSource = ddl;
   DdPetPist.DataValueField = "Specie";
   DdPetPist.DataTextField = "Specie";
   DdPetPist.DataBind();
   cs.Close();
   cs.Dispose();
}

选择索引更改
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   MySqlCommand cd = new MySqlCommand("SELECT CAST(Specie AS varchar) + '#' + CAST(Specie_Price AS varchar) AS Specie FROM pets", cs);
   cs.Open();
   PetPrice.Text = Convert.ToString(cd.ExecuteReader());
   cs.Close();
}

请任何帮助将是伟大的,我已经被困在这个问题上几个小时,并想继续我的下一个任务在手。

最佳答案

我会这样做:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string selection = DropDownList1.SelectedValue;
    string petPrice = string.Empty;

    MySqlCommand cd = new MySqlCommand(String.Format("SELECT Specie_Price FROM pets WHERE Specie ='{0}'",selection), cs);
    cs.Open();
    petPrice = Convert.ToString(cd.ExecuteScalar());
    cs.Close();

    petPrice.Text = String.Format("{0}  is £{1}", selection, petPrice);
}

编辑:同样,在页面加载中,如果(!ispostback),如下所示:
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
       MySqlCommand cd = new MySqlCommand("SELECT * FROM pets", cs);
       cs.Open();
       MySqlDataReader ddl = cd.ExecuteReader();
       DdPetPist.DataSource = ddl;
       DdPetPist.DataValueField = "Specie";
       DdPetPist.DataTextField = "Specie";
       DdPetPist.DataBind();
       cs.Close();
       cs.Dispose();
    }
}

关于c# - C#Switch语句查询MYSQL数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20129253/

10-11 07:32