Search code examples
asp.netpageload

Call a button_click on page_load asp.net


I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event @ page_Load.

Here's a snippet:

EDIT: I have made some changes in my code

protected void Page_Load(object sender, EventArgs e)
{
   if (Session["Redirected"] != null)
    {
        if (Session["FirstName"] != null)
            txtSearch.Text = Session["FirstName"].ToString();
        if (Session["Gender"] != null)
            ddlGen.SelectedValue = Session["Gender"].ToString();
        btnSearch_Click(sender, e);
    }

    if (!Page.IsPostBack)
    {
        BindGrid();
    }
}

and here's the click event:

protected void btnSearch_Click(object sender, EventArgs e)
{
    string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";

    if (txtSearch.Text != "")
    {
        query += " and FirstName like '%" + txtSearch.Text + "%'";
        Session["FirstName"] = txtSearch.Text;
    }
    if (ddlGen.SelectedValue != "")
    {
        query += "  and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
        Session["Gender"] = ddlGen.SelectedValue;
    }


    DataSet ds = new DataSet("Employees");
    SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
    SqlDataAdapter da = new SqlDataAdapter(query, con);            


    da.Fill(ds);
    gvSession.DataSource = ds;
    gvSession.DataBind();


}

Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.


Solution

  • You should reset the session redirected variable so it doesn't fall in the same case.

    protected void Page_Load(object sender, EventArgs e)
    {
       if (Session["Redirected"] != null)
       {
            Session["Redirected"] = null;
            ....