Reputation: 91
C# question, I'm using a query string to pass information from one page to another. I'm attempting to add a value to my drop down list. I'm struggling to figure out how to do it. I've tried multiple things, but thought that an if else statement might solve my problem. It didn't. Can anyone help me add a value to my list?
using System;
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DropDownList1.Items.Add("Concert-Guns N Roses");
DropDownList1.Items.Add("Concert-Katy Perry");
DropDownList1.Items.Add("Performance-Blue Man Group");
DropDownList1.Items.Add("Comic-Howie Mandel");
DropDownList1.Items.Add("Circus-Barnum and Bailey");
}
}
protected void BtnViewCart_Click(object sender, EventArgs e)
{
{
if (DropDownList1.SelectedIndex == 0)
{
DropDownList1.SelectedValue = "75.00";
}
else if (DropDownList1.SelectedIndex == 1)
{
DropDownList1.SelectedValue = "65.00";
}
else if (DropDownList1.SelectedIndex == 2)
{
DropDownList1.SelectedValue = "40.00";
}
else if (DropDownList1.SelectedIndex == 3)
{
DropDownList1.SelectedValue = "28.00";
}
else if (DropDownList1.SelectedIndex == 4)
{
DropDownList1.SelectedValue = "25.00";
}
decimal gnrTicket = Convert.ToDecimal(DropDownList1.SelectedValue[0]);
decimal kpTicket = Convert.ToDecimal(DropDownList1.SelectedValue[1]);
decimal bmgTicket = Convert.ToDecimal(DropDownList1.SelectedValue[2]);
decimal hmTicket = Convert.ToDecimal(DropDownList1.SelectedValue[3]);
decimal bbTicket = Convert.ToDecimal(DropDownList1.SelectedValue[4]);
}
if (DropDownList1.SelectedIndex == -1)
{
labelError.Text = "You Must Select a Show!";
}
else
{
string url = "Output.aspx?";
url += "Item=" + DropDownList1.SelectedItem.Text + "& <br />";
url += "Price=" + DropDownList1.SelectedItem.Value + "& <br />";
url += "Mode=" + RadioButton1.Checked.ToString();
Response.Redirect(url);
}
}
}
Upvotes: 1
Views: 244
Reputation: 68
As a good practice, it is probably best not to try to resolve this in the Click event handler, and to simplify the code. We can do this by learning more about the ListItem class. (See MSDN for more information.)
In one of its overloads, a ListItem has two components -- a text value and a data value. For example:
// Create a ListItem
ListItem li = new ListItem("MyText", "MyValue");
// Add it to the DropDownList
MyDropDownList.Items.Add(li);
Therefore, you can save having to do all of that logic in the Click event handler by assigning the values with their label counter parts. Your values are numeric in your code above, but you can parse them to Decimal or Double data types later.
You can do the above in one step if you wish. I just expanded it to illustrate. For example:
DropDownList1.Items.Add("Concert-Guns N Roses", "75.00");
Does this help?
Upvotes: 2