删除行后,Gridview不会刷新

时间:2015-08-22 19:23:57

标签: asp.net sql-server gridview sqldatasource

我在GridView中有一个UpdatePanel

当我添加一行时,它会立即更新。问题是,当我删除一行时,它不会更新GridView

可以做些什么?

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.QueryString["EventId"] != null)
        {
            ExtractEventData();
            GridView1.DataSourceID = "SqlDataSource1";
        }
    }
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
     string CS = 
       ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
     using (SqlConnection con = new SqlConnection(CS))
     {
         con.Open();
         SqlCommand cmd = new SqlCommand("spInsertComment", con);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@Comment", txtComment.Text);
         cmd.Parameters.AddWithValue("@Eventid", lblEventId.Text);
         cmd.Parameters.AddWithValue("@UserId", Session["UserId"].ToString());
         cmd.ExecuteNonQuery();
         txtComment.Text = "";
         GridView1.DataSourceID = "SqlDataSource1";
         GridView1.DataBind();
     }
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int id = Int32.Parse(e.CommandArgument.ToString());
        string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(
              "Delete from tblEventComments WHERE CommentId = @CommentId", con);
            cmd.Parameters.AddWithValue("@CommentId", id);
            cmd.ExecuteNonQuery();
            GridView1.DataSourceID = "";
            GridView1.DataSourceID = "SqlDataSource1";
            GridView1.DataBind();
        }
    }
}

我还尝试从datasource1删除GridView连接,然后重新分配它。它仍然似乎无法正常工作,我需要的方式。

我认为您不需要GridView标记,但是如果有必要,您可以提出要求。

1 个答案:

答案 0 :(得分:0)

根据this帖子,您应该使用GridView.DeleteRow方法删除该行。