Analytics

顯示具有 GridView 標籤的文章。 顯示所有文章
顯示具有 GridView 標籤的文章。 顯示所有文章

2017年2月20日 星期一

[GridView]如何 使用GridView做出動態排序與超連結 ( How to use the GridView to make dynamic sorting and hyperlinks)


問題
如何 使用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
}

2016年6月28日 星期二

[CSS]如何 讓GridView超出高度時自動顯示捲軸 (Automatic display scroll how GridView exceed height)


問題
如何 讓GridView超出高度時自動顯示捲軸



解決方法
<style type="text/css">
 #grid-view-container
{
      height: auto;
      overflow: scroll;
      max-height: 450px;
 }
</style>

<div id="grid-view-container" style="width:98%;height:380px;z-index:99999;margin-left:5px;margin-top:5px;">
gridview here....
<div>

2015年10月14日 星期三

[GridView]使用 GridView做出排序效果 (Make use GridView sorting effect)


問題
使用 GridView做出排序效果



解決方法
.aspx
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" Width="100%" AllowSorting="True" OnSorting="gvData_Sorting">

<Columns>...</Columns>

</asp:GridView>
.cs
private static Hashtable ht;//定義暫存變數
private static Hashtable sort;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ht = null ?? new Hashtable();//初始化暫存變數
        sort = null ?? new Hashtable();

        DataTable dt = queryData();
        ht[userid] = dt;//資料暫存於變數
        gvData.DataSource = dt;
        gvData.DataBind();
    }
}
protected void gvData_Sorting(object sender, GridViewSortEventArgs e)
{
    SetSortDirection((string)sort[userid]);//傳入排序資料變數
    if (ht[userid] != null)
    {
        //Sort the data.
        DataTable dt = (DataTable)ht[userid];//取出暫存變數
        dt.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
        gvData.DataSource = dt;
        gvData.DataBind();
        sort[userid] = _sortDirection;//排序資料暫存於變數
    }
}
string _sortDirection;
protected void SetSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
        _sortDirection = "DESC";
    else
        _sortDirection = "ASC";
}

[GridView]使用 BoundField DataFormatString 自訂日期格式 (BoundField DataFormatString use custom date format)


問題
使用 BoundField DataFormatString 自訂日期格式



解決方法
<asp:BoundField DataField="APPLY_DATE" DataFormatString="{0:yyyy-MM-dd hh:mm:ss}" HeaderText="進件日期" >
</asp:BoundField>

2013年12月20日 星期五

[GridView]使用 LinkButton另開視窗 (Use LinkButton open another window)


問題
使用 LinkButton另開視窗



解決方法
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string selectEntity = ((LinkButton)e.Row.Cells[0].FindControl("lkbENTITY")).Text.Trim();

        ((LinkButton)e.Row.Cells[0].FindControl("lkbENTITY")).OnClientClick = string.Format("window.open('{0}');", "http://192.168.2.1/default.aspx?entity="+ selectEntity 
    }
}

2013年9月24日 星期二

[ASP.NET]使用 CSS固定GridView表頭 (Use CSS fixed GridView header)


問題
使用 CSS固定GridView表頭



解決方法
用在Masterpage下:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
table th
{
    background-color: Gray;
    position: relative;
    top: expression(this.offsetParent.scrollTop);                  
}
</style>
用在一般asp.net網頁:
<style type="text/css">
.fixedHeader
{
    overflow: auto;
    height: 150px;
}
table th
{
    position: relative
    top: expressio(this.parentNode.parentNode.parentNode.scrollTop-1)
}
</style>

2013年8月2日 星期五

[ASP.NET]解決 Gridview匯出excel時內容變成亂碼 (Export Gridview resolve when garbled excel content)


問題
Gridview匯出excel時內容變成亂碼



解決方法
public void ExportExcelFromGridView(GridView gv)
{
    string filename = "Excel1.xls";      
    HttpContext.Current.Response.ClearContent();
    //fix 亂碼加入下行
    HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter sw = new System.IO.StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gd.RenderControl(htw);
    HttpContext.Current.Response.Write(sw.ToString());
    HttpContext.Current.Response.End();
}

2013年6月26日 星期三

[ASP.NET]使用 GridView.Caption add header (Use GridView.Caption add header)


問題
使用 GridView.Caption add header



解決方法
<asp:GridView ID="GridView1" runat="server" ...

Caption='<table border="1" width="100%" cellpadding="0" cellspacing="0" bgcolor="yellow"><tr><td>Grid Heading</td></tr></table>'

CaptionAlign="Top">

source:http://forums.asp.net/t/966407.aspx/1

2013年5月9日 星期四

[ASP.NET]解決 匯出EXCEL時發生 RegisterForEventValidation 只能在 Render(); 期間呼叫 (EXCEL RegisterForEventValidation resolve occurred while exporting only Render (); call during)


問題
將GridView匯出成Excel時,發生 解決 匯出EXCEL時發生 RegisterForEventValidation 只能在 Render(); 期間呼叫



解決方法
.aspx裡的<%page%>標籤,加入下面2行:
EnableEventValidation = "false"
AutoEventWireup="true"

2013年3月21日 星期四

[ASP.NET]使用 HtmlTextWriter匯出GridView時移除GridView上的超連結 (Remove hyperlink on the GridView using HtmlTextWriter Export GridView)


問題
使用 HtmlTextWriter匯出GridView時移除GridView上的超連結



解決方法
RemoveGridViewLink(gridview1);
ExportGridView(gridview1);

Sample code:

public void RemoveGridViewLink(Control targetGridView)
{
    LinkButton lb = new LinkButton();
    Literal l = new Literal();
    string name = string.Empty;
    for (int i = 0; i < targetGridView.Controls.Count; i++)
    {
        if (targetGridView.Controls[i].GetType() == typeof(LinkButton)
|| targetGridView.Controls[i].GetType() == typeof(HyperLink)
|| targetGridView.Controls[i].GetType().BaseType == typeof(LinkButton)
|| targetGridView.Controls[i].GetType().BaseType == typeof(HyperLink))
        {
            l.Text = (targetGridView.Controls[i] as LinkButton).Text;
            targetGridView.Controls.Remove(targetGridView.Controls[i]);
            targetGridView.Controls.AddAt(i, l);
        }
        if (targetGridView.Controls[i].HasControls())
            RemoveGridViewLink(targetGridView.Controls[i]);
    }
}

public void ExportGridView(GridView gv)
{
gv = RemoveGridViewLink(Control gv);
    string attachment = "attachment; filename=file.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    HtmlForm frm = new HtmlForm();
    gv.Parent.Controls.Add(frm);
    frm.Attributes["runat"] = "server";
    frm.Controls.Add(gv);

    frm.RenderControl(htw);

    Response.Write(sw.ToString());
    Response.End();
}

public override void VerifyRenderingInServerForm(Control control){}

[ASP.NET]使用 GridView.RowDataBond事件置換樣板欄位裡的控制項 (Use GridView.RowDataBound event replacement model in the field of controlled items)


問題
使用 GridView.RowDataBond事件置換樣板欄位裡的控制項



解決方法
if (e.Row.RowType == DataControlRowType.DataRow)
{
//第2欄的超連結
int i =2;
if (e.Row.Cells[i].Controls[1].GetType() == typeof(LinkButton))
{
if (e.Row.Cells[0].Text.Trim() == "Total")//置換行頭為total的欄位控制項
{
LinkButton lbtn = (LinkButton)e.Row.Cells[i].Controls[1];
Label lbtemp = new Label();
//控制項一定要給id,不然在底下移除時,會移錯控制項
lbtemp.ID = string.Format("lb{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
lbtemp.Text = lbtn.Text;
e.Row.Cells[i].Controls.Add(lbtemp);

e.Row.Cells[i].Controls.Remove(lbtn);//移除原本控制項
}
}
}

2013年3月14日 星期四

[ASP.NET]使用 GridView.TemplateField 加入自動編號欄位 (Use GridView TemplateField added AutoNumber field)


問題
使用 GridView.TemplateField 加入自動編號欄位



解決方法
<asp:TemplateField>
    <HeaderTemplate>
        <asp:Label ID="lbItemTille" runat="server" Text="ITEM"></asp:Label>
    </HeaderTemplate>
    <ItemTemplate >
       <%#Container.DataItemIndex+1 %>
    </ItemTemplate>
    <HeaderStyle BackColor="Blue" CssClass="arial_12_white" />
    <ItemStyle HorizontalAlign="Center" />
 </asp:TemplateField>

2012年4月9日 星期一

[ASP.NET]使用 TableCell取得GridView裡樣板所選到的資料(Use TableCell get the GridView to the data of the selected template)


問題
使用 TableCell取得GridView裡樣板所選到的資料
樣版裡可以自定按鈕,若按下按鈕時,取得目前這一筆資料



解決方法
Button btn = (Button)sender;//取得目前按鈕
TableCell tc = (TableCell)btn.Parent;//取得目前table欄位
//將grid view對應到table的row
GridViewRow gvr = (GridViewRow)tc.Parent;
int rowindex = gvr.RowIndex;//取出目前的index
//gv_Hotel若有設定key可用此取key
this.lbHotelId.Text = Convert.ToString(gv_Hotel.DataKeys[rowindex].Value);
//取grid view顯示的欄位1資料
this.tbHotel.Text = Convert.ToString(gv_Hotel.Rows[rowindex].Cells[1].Text);

2011年4月19日 星期二

[GridView]使用 BoundField 呈現斷行效果(Use line breaks BoundField rendering effect)


問題
使用GridView顯示資料時,資料需要呈現斷行效果



解決方法

1.資料來源(這邊是用DB當資料來源)的後方,加上html的斷行符號<br />
讓資料看起來像這樣:
Capture
2.在GridView需要斷行效果的欄位裡,將HtmlEncode屬性設為false:
Capture1
GridView的呈現效果:
Capture2

2011年4月11日 星期一

[GridView]使用 TemplateField CheckBox繫結資料方式(Use TemplateField CheckBox tying Profile Information)


問題

使用 TemplateField CheckBox繫結資料方式



解決方法

當使用CheckBox當GridView裡的TempleteField時,可以使用以下方式繫結資料來源,注意的是只能是0跟1的整數值歐!!
CheckBox裡的Checked屬性加上一句就可以了.
<asp:GridView ID="GridView1" runat="server" />
 <asp:TemplateField HeaderText="啟用"> 
  <ItemTemplate> 
   <asp:CheckBox ID="cbLock" Enabled="True" Checked='<%# Bind("Lock") %>' runat="server" oncheckedchanged="cbLock_CheckedChanged" AutoPostBack="True" EnableViewState="False" /> 
  </ItemTemplate>
  <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
 </asp:TemplateField> 
</asp:GridView>

另外若要取得Checkbox的資料做判斷的話,方式如下:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  //取得目前的checkbox
  CheckBox cb = (CheckBox)e.Row.FindControl("cbLock");
  cb.Enable=false;//關閉控制項
 }
}

[GridView]使用 TableCell特性取GridView裡的ButtonFiled欄位的值(TableCell characteristic value for use in the GridView ButtonFiled take the field)


問題
使用 TableCell特性取GridView裡的ButtonFiled欄位的值



解決方法
一個ButtonFiled型態是一個位於TableCell裡的控制項,所以如果要從Gridview取得某row的某column的控制項時,可採用以下方式:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
//row裡的第1個column裡的第一個控制項
((Button)e.Row.Cells[0].Controls[0]).Enabled = true;
    }
}

[GridView]使用 TableCell特性取GridView的BoundFiled欄位的值(Get BoundFiled value in GridView control)


問題

使用 TableCell特性取GridView的BoundFiled欄位的值



解決方法

一個BoundFiled型態是一個TableCell,所以如果要從Gridview取得某row的某column的值時,可採用以下方式:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{
    if (e.Row.RowType == DataControlRowType.DataRow) 
    {  
      string name=(TableCell)e.Row.Cells[0]).Text;
    } 
}

2011年3月25日 星期五

[ASP.NET]解決 GridView 匯出Excel 發生Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."


問題

GridView 匯出Excel 發生Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."



解決方法

語法如下:
protected void btnExportExcel_Click(object sender, EventArgs e)
{ 
 if (GridView1.Rows.Count > 0) 
 { 
  string attachment = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss"))); 
  Response.ClearContent(); 
  Response.AddHeader("content-disposition", attachment); 
  Response.ContentType = "application/ms-excel";
  StringWriter sw = new StringWriter(); 
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  GridView1.RenderControl(htw); 
  Response.Write(sw.ToString()); 
  Response.End(); 
 } 
}
但是會發生錯誤下:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
解決方式override 原有的function:
public override void VerifyRenderingInServerForm(Control control)
{
 
}

[ASP.NET]使用 GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全(Use Export GridView complete EXCEL solve Gridview Pagination incomplete)


問題
GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全
當GridView有設定分頁的時候,會發生多頁的時候,EXCEL卻只會出某一頁,如下:
string attachment  = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();




解決方法
解決方式其實很簡單,在respose到client前,重新指定GridView的PageSize就可以了!如下:
ReportViewPool.allocationInvoiceDataTable tb = DataLoad();//自訂義tb GridView1.DataSource = tb;
GridView1.PageSize = tb.Rows.Count;//重新指定頁面筆數
GridView1.DataBind();//指定以後依定要bind一次
string attachment = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

2011年3月14日 星期一

[ASP.NET]使用 GridView.TemplateField實作Link Button觸發下載檔案的動作(Use GridView.TemplateField implementation Linkbutton trigger action download files)


問題
使用 GridView.TemplateField實作Link Button觸發下載檔案的動作



解決方法
在LinkButton事件哩,加入程式碼: .cs
protected void lbtFileName_Click(object sender, EventArgs e)
{    
 LinkButton btn = (LinkButton)sender;
    TableCell tc = (TableCell)btn.Parent;
    GridViewRow gvr = (GridViewRow)tc.Parent;
    int rowindex = gvr.RowIndex;
        //資料來源
    DataTable tb = db.GetContentByGID(Convert.ToInt32(gvNotice.DataKeys[rowindex].Value));
    DataRow row = tb [0];    //下載檔案
    Response.Clear();
    string fileName = Server.UrlPathEncode(Convert.ToString(row["FileName"]));
    Response.Expires = 0;
    Response.Buffer = true;
    Response.AddHeader("Accept-Language", "zh-tw");
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));     //Response.Cache.SetNoStore();
    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Length", row.NContent.Length.ToString());
    Response.BinaryWrite(row.NContent);
    Response.End();
}
.aspx
設定LinkButton顯示的文字:
<asp:TemplateField HeaderText="文件名稱" SortExpression="FileName">
<ItemTemplate>
<asp:LinkButton ID="lbtFileName" runat="server" CommandName="OpenFile" onclick="lbtFileName_Click"  > <%#Eval("FileName") %></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

熱門文章