I am trying to refresh the grid-view after insert but it’s not working for me, here is my code:
<asp:TextBox ID="TimeBox" runat="server" />
<asp:TextBox ID="CommentBox" runat="server" TextMode="MultiLine" />
<asp:Button ID="insButton" runat="server" OnClick="insert" Text="Insert" />
<asp:GridView ID="MainGrid" runat="server">
</asp:GridView>
and here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
// filling the grid view
SqlConnection conn = new SqlConnection (@"connectionString");
SqlCommand cmd = new SqlCommand("SELECT tim,com FROM ten",conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
MainGrid.DataSource = ds;
MainGrid.DataBind();
}
protected void insert(object sender, EventArgs e) //adding the comments
{
SqlConnection conn = new SqlConnection(@"connectionString");
SqlCommand cmd = new SqlCommand("INSERT INTO tennis (tim,com) VALUES (@tim,@com)", conn);
cmd.Parameters.AddWithValue("@tim", TimBox.Text);
cmd.Parameters.AddWithValue("@com", ComBox.Text);
conn.Open();
cmd.ExecuteNonQuery();
MainGrid.DataBind();
conn.Close();
}
the insert works fine and i can see the data if I refresh the page but I am trying to refresh the grid view only without refreshing the page.
After inserting the new record, you have to re-query the database and rebind the grid (same as you do in Page_Load) with a datasource which includes the new, inserted record.