[英]Refresh GridView After Data is Deleted From DetailView Using C#
當用戶從GridView中選擇任何記錄時,我的DetailView將根據GridView的選擇進行更新。 所以我想要做的是,當我從DetailView中刪除任何東西然后我想刷新GridView所以基本上我不想在GridView中顯示已刪除的記錄。 我試圖通過在連接和SQL語句之后執行數據綁定來解決此問題,但它不會刷新它。 需要注意的一點是我使用的是Accordion窗格,但我的gridview和detailview都在同一個窗格中。 我不確定這是否會破壞任何東西。 這是我的代碼:
protected void Refresh_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
您可以使用名為“ItemDeleted”的數據視圖的事件,如下所示:
DetailViewName_ItemDeleted(object sender,
DetailsViewDeletedEventArgs e)
{
// Refresh the GridView control after a new record is updated
// in the DetailsView control.
GridViewName.DataBind();
}
以上代碼來自官方MSDN網站,用於詳細視圖控制。
另一種方式(我更喜歡)是在Page_load
過程中處理數據網格,因此當您在詳細視圖中按下刪除按鈕時,頁面將執行回發。
因此,在過程Page_load
您可以調用另一個填充數據網格的過程。 代碼可能是這樣的:
if (isPostback)
{
FillGrid();
}
private void FillGrid()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
您的代碼沒有顯示實際刪除記錄的任何內容,因此當您重新獲取數據時仍然包含所有內容是可以理解的。
你需要做的是:
如果您按照這3個步驟進行操作。
嘗試使用從DGV按下刪除鍵時調用的事件
private void DGV_DeleteKeyPressed(object sender, KeyEventArgs e)
{
//enter code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.