問題
如何 使用GridView做出動態排序與超連結
解決方法
.aspx
<asp:GridView ID="gvResult" runat="server" OnDataBound="gvContent_DataBound" OnPreRender="gvContent_PreRender" EmptyDataText="No Data" AllowSorting="True" OnSorting="gvResult_Sorting" CellSpacing="1" BorderColor="Black" HeaderStyle-BackColor="Blue" HeaderStyle-ForeColor="White"> <RowStyle HorizontalAlign="Center" Wrap="False" BorderWidth="1px" BorderColor="Black" /> <HeaderStyle BackColor="Blue" ForeColor="White" HorizontalAlign="Center" /> </asp:GridView>.cs
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) InitData(); } private void InitData() { DataTable data = get source.... ViewState["data"] = data; ViewState["dataSortName"] = ""; ViewState["dataSortSeq"] = ""; this.gvResult.DataSource = data; this.gvResult.DataBind(); } protected void gvResult_Sorting(object sender, GridViewSortEventArgs e) { if (ViewState["dataSortName"].ToString() == e.SortExpression) if (ViewState["dataSortSeq"].ToString() == "ASC") ViewState["dataSortSeq"] = "DESC"; else ViewState["dataSortSeq"] = "ASC"; else { ViewState["dataSortName"] = e.SortExpression; ViewState["dataSortSeq"] = "ASC"; } DataTable data = (DataTable)ViewState["data"]; data.DefaultView.Sort = string.Format("{0} {1}", ViewState["dataSortName"], ViewState["dataSortSeq"]); data = data.DefaultView.ToTable(); this.gvResult.DataSource = data; this.gvResult.DataBind(); ViewState["data"] = data; } protected void gvContent_DataBound(object sender, EventArgs e) { } protected void gvContent_PreRender(object sender, EventArgs e) { DataTable data = (DataTable)ViewState["data"]; if (data == null || data.Rows.Count == 0) return; //以下是動態超連結...可不做 #region 取得欄位的位置 int productIndex = 0; for (int i = 0; i < gvResult.HeaderRow.Cells.Count; i++) { if (((LinkButton)(gvResult.HeaderRow.Controls[i].Controls[0])).Text == "PRODUCT_ID")//須超連結的欄位 productIndex = i; } #endregion #region 須超連結的欄位 foreach (GridViewRow gvItem in gvResult.Rows) { LinkButton obj = new LinkButton(); obj.Text = gvItem.Cells[productIndex].Text.Trim(); obj.OnClientClick = string.Format(@"javascript:subpop('www.google.com/tw?product={0}');return false;", product); gvItem.Cells[productIndex].Controls.Add(obj); } #endregion }
沒有留言:
張貼留言