mohd qais
mohd qais

Reputation: 11

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Default2 : System.Web.UI.Page
{
    static string startdate;
    DataTable dt;
    static string enddate;
    static string EstDate;
    string str = @"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";

    protected void Page_Load(object sender, EventArgs e)
    {//Page dosn't go back//
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        Response.Cache.SetNoStore();





        if (IsPostBack)
        {
            if (Session["auth"] != "ok" )
            {
                Response.Redirect("~/Login.aspx");


            }
            else if (Session["desg"] != "Scrum Master")
            {
                //Response.Redirect("~/errorpage.aspx");
                addtaskbtnPannel.Visible = false;
            }


        }
        else
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
            if (Session["auth"] != "ok")
            {

                Response.Redirect("~/Login.aspx");

            }
            else if (Session["desg"] != "Scrum Master")
            {
               // Response.Redirect("~/errorpage.aspx");
                addtaskbtnPannel.Visible = false;
            }

        }

         //decode url data in query string
        labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
        labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
        labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
        String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
        string query = "Select * from Tasks where S_ID=" + labelID.Text;
        SqlConnection con = new SqlConnection(str);
        SqlCommand com = new SqlCommand(query, con);
        con.Open();
        SqlDataReader sdr = null;
        sdr = com.ExecuteReader();
        dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
        while (sdr.Read())
        {
            dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();
        con.Close();
        if (!IsPostBack)
        {
            PanelTaskForm.Visible = false;
            Panel1.Visible = false;
        }
        else if(IsPostBack){
            PanelTaskForm.Visible = true;
            Panel1.Visible = true;
        }
    }
    protected void saveTask_Click(object sender, EventArgs e)
    {
          string str = @"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
        try
        {

            String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
            SqlConnection con = new SqlConnection(str);
            SqlCommand com = new SqlCommand(query, con);
            con.Open();

            if (com.ExecuteNonQuery() == 1)
            {
                TaskStatus.Text = "Task Successfully Saved ";
                GridView1.DataBind();

            }
            else
            {

                TaskStatus.Text = "Task not Saved";
            }

        }
        catch (Exception ex)
        {
            Response.Write("reeor" + ex);
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void TaskDesBox_TextChanged(object sender, EventArgs e)
    {


    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Calendar1.Visible = true;
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
        SDate.Text = startdate;
        Calendar1.Visible = false;
    }

    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        Calendar2.Visible = true;
    }

    protected void Calendar2_SelectionChanged(object sender, EventArgs e)
    {
        EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
        EstDateBox.Text = EstDate;
        Calendar2.Visible = false;



    }

}

Upvotes: 1

Views: 112

Answers (1)

Dacker
Dacker

Reputation: 892

What you are doing on a post back is:

  1. First show the results due to code in your Page_Load
  2. Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.

Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack). And at the end of saveTask_Click you have to update your grid view again.

So move the code you need to show the grid view to a method you can call on other occasions:

protected void ShowGridView() {
    String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
    string query = "Select * from Tasks where S_ID=" + labelID.Text;
    SqlConnection con = new SqlConnection(str);
    SqlCommand com = new SqlCommand(query, con);
    con.Open();
    SqlDataReader sdr = null;
    sdr = com.ExecuteReader();
    dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
    while (sdr.Read())
    {
        dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
    }

    GridView1.DataSource = dt;
    GridView1.DataBind();
    con.Close();
}

Then call it in your Page_Load on !IsPostBack

    if (!IsPostBack)
    {
        ShowGridView();
        PanelTaskForm.Visible = false;
        Panel1.Visible = false;
    }
    else if(IsPostBack){
        PanelTaskForm.Visible = true;
        Panel1.Visible = true;
    }

Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.

       if (com.ExecuteNonQuery() == 1)
        {
            TaskStatus.Text = "Task Successfully Saved ";
            //GridView1.DataBind();
            ShowGridView();
        }
        else
        {

            TaskStatus.Text = "Task not Saved";
        }

Upvotes: 1

Related Questions