0

好的,我遇到的问题是下拉列表。下拉列表应该输出(Drinklabel)选定的值,它会这样做但仅是列表中的第一个(下拉列表由会话变量生成)。

我想要它,所以我可以使用下拉列表,选择新值然后让标签(Drinklabel)自行更新。

*下面的代码*

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Drinklabel.Text = "Your Chosen Beverage is A " + DropDownList1.SelectedValue.ToString() + " Drink.";
    }

///////////////////////////////////////// //////////

完整的页面代码

public partial class About : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        MyFruit = Session["Fruitname"] as List<string>;
        //Create new, if null
        if (MyFruit == null)
            MyFruit = new List<string>();
        DropDownList1.DataSource = MyFruit;
        DropDownList1.DataBind();

    }

    public List<string> MyFruit { get; set; }

    protected void ButtonCalculate_Click(object sender, EventArgs e)
    {
        decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
                                       TextBoxQuantity.Text.Trim());

        LabelResult.Text = "You would like " + TextBoxQuantity.Text.Trim() +
            DropDownList1.SelectedItem.Text + "(s) for a total of $" +
            total.ToString();
    }

    private decimal calculatePrice(string p1, string p2)
    {
        throw new NotImplementedException();
    }

    private decimal calculatePrice(string fruitName, int quantity)
    {
        // Ask the database for the price of this particular piece of fruit by name
        decimal costEach = GoToDatabaseAndGetPriceOfFruitByName(fruitName);

        return costEach * quantity;
    }

    private decimal GoToDatabaseAndGetPriceOfFruitByName(string fruitName)
    {
        throw new NotImplementedException();
    }


}
4

1 回答 1

1

在将会话对象分配给 Local List 之前,您没有检查会话对象MyFruit

因此在分配Session对象之前添加检查

替换这个:

MyFruit = Session["Fruitname"] as List<string>;

有以下内容:

if(Session["Fruitname"]!=null)
MyFruit = Session["Fruitname"] as List<string>;

在你的问题中你说你总是只能得到一个项目DropDownList。但在这里你只分配Session一次对象,所以很明显你会得到一个项目。

于 2013-11-10T13:49:32.083 回答