Reputation: 19
In my code, after i choose the value in the drop down list and hit enter it send the first value of the drop down list instead
May I know what are the possible causes?
Below is my code:
protected void Button1_Click(object sender, EventArgs e)
{
if (DayBox.Text != "" && MonthBox.Text != "" && YearBox.Text != "")
{
string date;
int container = Convert.ToInt32(DayBox.Text);
if (container < 10)
{
date = String.Format("0{0}/{1}/{2}", DayBox.Text, MonthBox.Text, YearBox.Text);
}
else
{
date = String.Format("{0}/{1}/{2}", DayBox.Text, MonthBox.Text, YearBox.Text);
}
Session["DATE"] = date;
Session["IPADDRESS"] = IPDropDownList.Text;
Response.Redirect("IPAddressDay.aspx");
}
}
Code for the dropdown box:
//this if statment is for gettting the ip address for that Month;
if (DayBox.Text == "" && MonthBox.Text != "" && YearBox.Text != "")
{
IPDropDownList.Items.Clear();
string date;
date = String.Format("{0}/{1}",MonthBox.Text, YearBox.Text);
sqlStatment = String.Format("SELECT IPAddress FROM IPActivity WHERE AccessDate LIKE '%{0}' GROUP BY IPAddress;", date);
MyDataSet = RetriveDataBase(connection, sqlStatment, tableName);//method written by me
dra = MyDataSet.Tables[tableName].Rows;
foreach (DataRow dr in dra)
{
IPDropDownList.Items.Add(dr[0].ToString());
}
//this is to close the if statment for gettting the ip address for that Month;
}
Description: It will not read the value I choose, but take the first value instead and send to next page
Upvotes: 0
Views: 924
Reputation: 4960
You need:
Session["IPADDRESS"] = IPDropDownList.SelectedValue;
As select boxes have a value property which gets the value of the option which can differ from the text displayed.
Upvotes: 0
Reputation: 19241
Assuming you fill your DropDownList at your Page_Load
event, you need to use IsPostBack
. Everytime you hit the button Page_Load
event is fired before your Button1_Click
event. Therefore, at your Button1_Click
you get the first value in dropdownlist always. Correct code should be,
if (!IsPostBack && DayBox.Text == "" && MonthBox.Text != "" && YearBox.Text != "")
{
IPDropDownList.Items.Clear();
string date = String.Format("{0}/{1}",MonthBox.Text, YearBox.Text);
sqlStatment = String.Format("SELECT IPAddress FROM IPActivity WHERE AccessDate LIKE '%{0}' GROUP BY IPAddress;", date);
MyDataSet = RetriveDataBase(connection, sqlStatment, tableName);
foreach (DataRow dr in MyDataSet.Tables[tableName].Rows;)
{
IPDropDownList.Items.Add(dr[0].ToString());
}
}
Upvotes: 1
Reputation:
Try this:
Session["IPADDRESS"] = IPDropDownList.SelectedValue;
then, to set the value:
IPDropDownList.SelectedValue = Session["IPADDRESS"] != null ? Session["IPADDRESS"].ToString() : "" ;
And don't reset your dropdownlist if you're posting back.
if(!IsPostBack)
{
//Code to set dropdownlist values here
}
Upvotes: 1