将值传递给下一页C#ASP.NET

时间:2011-08-19 10:18:16

标签: c# .net asp.net

在我的代码中,在我选择下拉列表中的值并按Enter后,它会发送下拉列表的第一个值

我可以知道可能的原因是什么吗?

以下是我的代码:

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");
    }
}

下拉框的代码:

//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;
}

描述: 它不会读取我选择的值,而是取第一个值并发送到下一页

3 个答案:

答案 0 :(得分:1)

假设您在Page_Load事件中填写DropDownList,则需要使用IsPostBack。每当您点击Page_Load按钮时,您的Button1_Click事件就会被触发。因此,在Button1_Click处,您始终会获得下拉列表中的第一个值。正确的代码应该是,

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());
    }   
}

答案 1 :(得分:1)

试试这个:

Session["IPADDRESS"] = IPDropDownList.SelectedValue;

然后,设置值:

IPDropDownList.SelectedValue = Session["IPADDRESS"] != null ? Session["IPADDRESS"].ToString() : "" ;

如果您要回发,请不要重置您的下拉列表。

if(!IsPostBack)
{
   //Code to set dropdownlist values here
}

答案 2 :(得分:0)

你需要:

Session["IPADDRESS"] = IPDropDownList.SelectedValue;

由于选择框有一个value属性,它获取的选项值可能与显示的文本不同。