我有两个下拉列表,第一个显示不同种类的动物,我希望第二个显示品种,具体取决于所选择的物种。
在我的数据库中,所有品种的品种都有匹配的ID。
首次下拉代码:
protected void Page_Load(object sender, EventArgs e)
{
DropDown_Species();
}
public void DropDown_Species()
{
if (!Page.IsPostBack)
{
MySqlCommand sql_country = new MySqlCommand("SELECT Species FROM breed", cs);
//connection string opend
cs.Open();
MySqlDataReader ddlvalue;
ddlvalue = sql_country.ExecuteReader();
petSpecies.DataSource = ddlvalue;
petSpecies.DataValueField = "Species";
petSpecies.DataTextField = "Species";
petSpecies.DataBind();
petSpecies.Items.Insert(0, "Select Species");
// connection string closed
cs.Close();
cs.Dispose();
}
}
第二次下拉代码:
protected void petsBreed_SelectedIndexChanged(object sender, EventArgs e)
{
if (petSpecies.Text != string.Empty)
{
MySqlCommand cd = new MySqlCommand(string.Format(
"SELECT * FROM (Breed.breed)", petSpecies.Text), cs);
cs.Open();
MySqlDataReader petsSpecies = cd.ExecuteReader();
petsBreed.DataSource = petsSpecies;
petsBreed.DataValueField = "Breed";
petsBreed.DataTextField = "Breed";
petsBreed.DataBind();
petsBreed.Items.Insert(0, "Select Breed");
cs.Close();
cs.Dispose();
}
我很确定问题出在第二次下拉。
对C#来说很新。
有人能告诉我问题出在哪里和/或如何使这个想法发挥作用?
答案 0 :(得分:0)
你正在使用string.Format
但没有使用那里的参数......?
MySqlCommand cd = new MySqlCommand(string.Format(
"SELECT * FROM (Breed.breed)", petSpecies.Text), cs);
你不应该使用字符串格式,如:
var use_it_properly = string.Format ("Hi {0}, now you're using it properly", name);
否则,你不会转发输入,在你的情况下应该是所选择的物种?
在MSDN上阅读更多内容:String.Format Method。
该网站的示例:
DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0);
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console.WriteLine(output);
// The example displays the following output:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
答案 1 :(得分:0)
我不熟悉MySQL。以下是您可以使用SqlDataSource执行的操作。
BreedId Species Breed
1 dog Alsatian
2 dog pitbull
3 dog Shetland sheepdog
4 dog Boxer
5 cat Dragon Li
6 cat Australian Mist
7 cat Korat
<asp:DropDownList ID="DropDownListSpecies" runat="server" DataSourceID="Species"
DataTextField="Species" DataValueField="Species" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="Species" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Species] FROM [Breed]"></asp:SqlDataSource>
<asp:DropDownList ID="DropDownListBreed" runat="server"
DataSourceID="breed" DataTextField="Breed" DataValueField="Breed">
</asp:DropDownList>
<asp:SqlDataSource ID="breed" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Breed] FROM [Breed] WHERE Species=@Species">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListSpecies"
PropertyName="SelectedValue" Name="Species" Type="String"
DefaultValue="cat" />
</SelectParameters>
</asp:SqlDataSource>
确保AutoPostBack="True"
DropDownListSpecies