1.綁定鍵值及讀取前端
前端設置:DataKeyNames=「Field1,Field2」;app
後臺設置:GridView1.DataKeyNames=Gridview1.DataKeyNames = new string[] { "PositionID", "DepartmentID" };ide
後臺讀取:string key=this.GridView1.DataKeys[i][0].ToString();this
2.可編輯列編碼
<asp:TemplateField HeaderText="Field1" ControlStyle-Width="100px" />
<ItemTemplate>
<asp:TextBox ID="Field1" runat="server" Text='<%# Bind("Field1") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>excel
3.斑馬線及鼠標停留變色orm
前端:onrowdatabound="GridView1_RowDataBound"server
後臺:seo
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++) //執行循環,保證每條數據均可以更新
{
if (e.Row.RowType == DataControlRowType.DataRow) //首先判斷是不是數據行
{
//當鼠標停留時更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#999'");
//當鼠標移開時還原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
if (i % 2 == 0)
this.GridView1.Rows[i].BackColor = System.Drawing.Color.Honeydew;
}
}string
4.導出EXCEL
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ContentEncoding = System.Text.Encoding.UTF8;//編碼不能錯,錯了就會亂碼,EXCEL解釋不了格式就把HTML文本所有顯示
Response.AppendHeader("Content-Disposition", "attachment;filename=SampleIssue.xls");
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
StringWriter sw= new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
/// <summary>
/// 導出EXCEL,要寫一個空的VerifyRenderingInServerForm方法
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
如出現錯誤提示「RegisterForEventValidation can only be called during Render();」,則在<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>裏面加入 EnableEventValidation="false"便可。