protected void gvBooks_RowEditing(object sender, GridViewEditEventArgs e)
{
//設定選中行
gvBooks.EditIndex = e.NewEditIndex;
//重新綁定數據
HRDataBind();
//獲取選中行的下拉框控件
DropDownList ddl = (DropDownList)gvBooks.Rows[e.NewEditIndex].FindControl("ddlCate");
//查詢綁定數據
ddl.DataSource = cm.GetAllCategories();
ddl.DataTextField = "Name";
ddl.DataValueField = "Id";
ddl.DataBind();
//查詢隱藏列
HiddenField hf = (HiddenField)gvBooks.Rows[e.NewEditIndex].FindControl("hfCateId");
ddl.SelectedValue = hf.Value;
}
#endregion
#region 取消編輯
protected void gvBooks_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//GV恢復正常狀態
gvBooks.EditIndex = -1;
//重新綁定數據
HRDataBind(); ;
}
#endregion
#region 更新
protected void gvBooks_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//獲取圖書Id
int id = Convert.ToInt32(gvBooks.DataKeys[e.RowIndex].Value);
//圖書名
string title = ((TextBox)gvBooks.Rows[e.RowIndex].FindControl("txtTitle")).Text;
//作者
string author = ((TextBox)gvBooks.Rows[e.RowIndex].FindControl("txtAuthor")).Text;
//類別id
DropDownList ddl = (DropDownList)gvBooks.Rows[e.RowIndex].FindControl("ddlCate");
int cateId = Convert.ToInt32(ddl.SelectedValue);
//根據Id查詢book
Books book = bm.QueryBookById(id);
book.Title = title;
book.Author = author;
book.Categories = new Categories() { Id = cateId };
//更新
bm.UpdateBook(book);
//更新完成恢復正常狀態
gvBooks.EditIndex = -1;
HRDataBind();
}
#endregion
#region 刪除
protected void gvBooks_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//獲取id
int id = Convert.ToInt32(gvBooks.DataKeys[e.RowIndex].Value);
//刪除
bm.DeleteBook(id);
//重新綁定
HRDataBind();
}
#endregion