在同一个asp.net页面中处理多个按钮

时间:2014-04-03 18:03:57

标签: c# asp.net ado.net

大家好我在同一个asp.net网页上使用两个按钮。这两个按钮包含不同的代码 第一个按钮从数据库中获取数据,这里是代码

protected void Button1_Click(object sender, EventArgs e)
{
    string username = Request.QueryString["username"];
    SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
    conn.Open();

    try 
    {
        string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
        SqlCommand com = new SqlCommand(checkaddress, conn);
        using (var reader = com.ExecuteReader())
        {
            while (reader.Read())
            {
                var tmp = reader["address"];
                if (tmp != DBNull.Value)
                {
                    laddress.Visible = true;
                    laddress.Text = reader["address"].ToString();
                }
                var cty = reader["city"];
                if (cty != DBNull.Value)
                {
                    lcity.Visible = true;
                    lcity.Text = reader["city"].ToString();
                }
                var zip = reader["zipcode"];
                if (zip != DBNull.Value)
                {
                    lzipcode.Visible = true;
                    lzipcode.Text = reader["zipcode"].ToString();
                }
            }
        }
    }
    finally
    {
        conn.Close();
    }
}

第二个按钮使用文本框值更新数据库中的值,这里是代码

protected void submit_Click(object sender, EventArgs e)
{
    string username = Request.QueryString["username"];
    string address=TextBox4.Text;
    string city=TextBox5.Text;
    string zipcode=TextBox6.Text;
    SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
    conn.Open();

    try 
    {
        string updateaddress = "UPDATE regforswa SET address=@address,city=@city,zipcode=@zipcode WHERE username="+username;
       SqlCommand com = new SqlCommand(updateaddress, conn);
       com.Parameters.AddWithValue("@address",address);
       com.Parameters.AddWithValue("@city",city);
       com.Parameters.AddWithValue("@zipcode",zipcode);
       // com.Parameters.AddWithValue("@username",username);
       if (com.ExecuteNonQuery() == 1)
       {
           result.Visible = true;
           result.Text = "congradulations.your address has been changed";
       }
       else
       {
           result.Visible = true;
           result.Text = "sorry please try again"; 
       }
    }
    catch(Exception ex)
    {
        Response.Write(ex.Message);
    }
    finally
    {
        conn.Close();
    }
}

但问题是当我点击第一个按钮时,与第二个按钮相关的验证控件不允许重新加载页面,因此我无法获取数据。

我的问题是,我们可以在同一网页上使用两个按钮,但具有不同的功能吗?

1 个答案:

答案 0 :(得分:1)

我认为您可以使用"验证组"解决你的问题。 http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx