1、格式化日期显示:
在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,将htmlencode设置为false,否则显示不了
默认设置为true,已防止XSS攻击,安全起见而用的,也可以用下列的模版列
<asp:TemplateField HeaderText="出生日期">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("FUserBirthDate","{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
2、HyperLinkField属性详解:
1、DataNavigateUrlFields:绑定到连接NavigateUrl属性的字段。其实就是指定,
DataNavigateUrlFormatString所设置的URL地址后面的参数,多个参数用逗号分隔,如:FUserID,FUserName
2、DataNavigateUrlFormatString:指定跳转的URL地址。如:
Default2.aspx?FUserID={0}&FUserName={1}
3、DataTextField:绑定到超链接的文本字段
4、Text:设置超链接上的文本,如果DataTextField没设置则显示此文本,如果DataTextField设置了,则显示数据库中对应字段的内容
3、常用格式化公式:
{0:C} 货币
{0:D4} 由0填充的4个字符宽的字段中显示整数;
{0:000.0}四舍五入小数点保留第几位有效数字;000.0小数点占一位,整数部分3个宽度,小于此宽度,前面补0,例:23.82格式化为023.8
{0:N2} 小数点保留2位有效数字;{0:N2}% 小数点保留2位有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd} 例如:
1977-7-20经{0:D}格式化后是1977年7月20日
1977-7-20经{0:d}格式化后是1977-7-20
1977-7-20经{0:yyyy-MM-dd}格式化后是1977-07-20
4、弹出查看详细对话框:
新窗口参数:window.open (url,null,'height=600,width=350,toolbar=no,menubar=no,
scrollbars=yes,resizable=yes,location=no,status=no');
例如:
<a href="#" onclick="javascript:varwin=window.open('Default2.aspx?FUserID=
<%#Eval("FUserID")%>',null,'width=600,height=350');">查看</a>
5、单元格内容换行:
正常换行,在Page_Load事件里设置:
GridView1.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
自动换行,在Page_Load事件里设置:
GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
指定某一列换行,在RowDataBound事件里设置:
e.Row.Cells[4].Style.Add("word-break", "break-all");
6、点击某标题排序:
1、首先设置此的SortExpression属性,指定排序字段,如:<asp:BoundField DataField="FUserName" HeaderText="姓名" SortExpression="FUserName" />
2、利用ViewState保存排序相关信息
3、书写相关代码
Page_Load事件部分
if (Page.IsPostBack == false)
{
ViewState["SortOrder"] = "FUserId"; //默认排序字段
ViewState["OrderDire"] = "ASC";
Bind();
}
绑定信息部分
public void Bind()
{
string strSql = "select * from TUser ";
DataSet ds = DbHelperOleDb.Query(strSql);//DbHelperOleDb.Query(strSql);
//为了排序获得DataView
DataView dv = ds.Tables[0].DefaultView;
//指定排序字段和方向
dv.Sort = ViewState["SortOrder"].ToString() + " " + ViewState["OrderDire"].ToString();
//GridView1.DataKeyNames = new string[] { "FUserId" }; 在设计页设了此属性,此处略
GridView1.DataSource = dv;
GridView1.DataBind();
}
排序事件部分
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["SortOrder"].ToString() == e.SortExpression)
{
ViewState["OrderDire"] = (ViewState["OrderDire"].ToString() == "Desc") ? "ASC" : "Desc";
}
else
{
ViewState["SortOrder"] = e.SortExpression;
}
Bind();
}
7、GridView里的下拉列表框DropDownList中的数据显示
//显示性别下拉列表
DropDownList ddl;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
DataRowView drv = ds.Tables[0].DefaultView[i];
if (drv["FUserSex"].ToString() == "男")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("ddlSex");
ddl.SelectedIndex = 0;
}
if (drv["FUserSex"].ToString() == "女")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("ddlSex");
ddl.SelectedIndex = 1;
}
}
8、突出显示某一单元格(例如金额低于多少,分数不及格等)
//突出显示起薪小于1000的
for (int i = 0; i <GridView1.Rows.Count; i++)
{
DataRowView drv = ds.Tables[0].DefaultView[i];
if (Convert.ToDouble(drv["FUserSalary"].ToString()) < 1000.00)
{
GridView1.Rows[i].Cells[7].BackColor = System.Drawing.Color.Red;
}
}
9、自动求和求平均值小计
//加入自动求和求平均值小计
for (int i = 0; i < GridView1.Rows.Count; i++)
{
DataRowView drv = ds.Tables[0].DefaultView[i];
if (String.IsNullOrEmpty(drv["FUserSalary"].ToString()) == false)
{
sum += Convert.ToDouble(drv["FUserSalary"].ToString());
}
}
Label3.Text ="¥"+ sum.ToString("f2");
10、点编辑按钮后,单元格显示相关控件
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
Bind();
}
11、取消编辑
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
Bind();
}
12、删除数据
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string strSql = "delete from TUser where FUserID='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
DbHelperOleDb.ExecuteSql(strSql);
Bind();
}
13、更新数据
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string strSql = "update Tuser set FUserSex='" +
//查找模板列的ddlSex控件,用FindControl方法
(GridView1.Rows[e.RowIndex].FindControl("ddlSex") as DropDownList).SelectedItem.Value + "',FUserName='" +
//以下两种数据类型转换都可以
(GridView1.Rows[e.RowIndex].Cells[3].Controls[0] as TextBox).Text.Trim() + "',FUserAddress='" +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.Trim() + "',FUserBirthDate='" +
(GridView1.Rows[e.RowIndex].Cells[6].Controls[0] as TextBox).Text.Trim() + "',FUserSalary=" +
//查找模板列编辑项的txtUserSalary控件,也用FindControl方法
(GridView1.Rows[e.RowIndex].FindControl("txtUserSalary") as TextBox).Text.Trim() + " where FUserID='" +
GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
DbHelperOleDb.ExecuteSql(strSql);
GridView1.EditIndex = -1;
Bind();
}
14、全选
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cb.Checked = (CheckBox2.Checked == true) ? true : false;
}
}
15、取消全选
protected void Button1_Click(object sender, EventArgs e)
{
CheckBox2.Checked = false;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
cb.Checked = false;
}
}
16、删除选择项
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox cb = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cb.Checked == true)
{
string strSql = "delete from TUser where FUserID='" +
GridView1.DataKeys[i].Value + "'";
DbHelperOleDb.ExecuteSql(strSql);
}
}
Bind();
}
17、显示隐藏某一列
protected void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
GridView1.Columns[5].Visible = CheckBox3.Checked;
}
18、鼠标移到GridView某一行时改变该行的背景色
在GridView1_RowDataBound事件中书写以下代码
//方法一:i=0第一条数据行背景不变色,使用要从i=-1开始
for (int i = -1; i < GridView1.Rows.Count; i++)
{
//判断是否是数据行
if (e.Row.RowType == DataControlRowType.DataRow)
{
//当鼠标停留时更改背景色
e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#00A9FF'");
//当鼠标移开时还原背景色
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
}
}
//方法二:如果是绑定数据行
if (e.Row.RowType == DataControlRowType.DataRow) //或e.Row.RowType != DataControlRowType.Header
{
//鼠标经过时,行背景色变
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#00A9FF'");
//鼠标移出时,行背景色变
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
19、弹出对话框
在GridView1_RowDataBound事件中书写以下代码
//实现删除时弹出确认对话框
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
((LinkButton)e.Row.Cells[10].Controls[0]).Attributes.Add("onclick",
"javascript:return confirm('你确认要删除:/"" + e.Row.Cells[3].Text + "/"吗?')");
}
}
20、实现自动编号
前台代码:
<asp:BoundField HeaderText="编号" ReadOnly="True" />
在GridView1_RowDataBound事件中书写以下代码
//实现自动编号
if (e.Row.RowIndex != -1)
{
int id = e.Row.RowIndex + 1;
//e.Row.Cells[1].Text本来绑定的事FUserId,这里给覆盖了
e.Row.Cells[1].Text = id.ToString();
}
21、单击一行的任意位置弹出新窗口
在GridView1_RowDataBound事件中书写以下代码
//单击一行的任意位置弹出新窗口,要获得e.Row.Cells[2].Text的值,把此列用户ID列改为BoundField列就可以
if(e.Row.RowIndex!=-1)
e.Row.Attributes.Add("onclick", "window.open('Default2.aspx?UserId="+e.Row.Cells[2].Text+"',null,'Toolbar=no')");
22、翻页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Bind();
}
完整前台代码Default.aspx如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="FUserID"
EmptyDataText="没有可显示的数据记录。" onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
PageSize="6" onrowupdating="GridView1_RowUpdating" onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound" onsorting="GridView1_Sorting"
AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FUserID" HeaderText="编号" ReadOnly="True" />
<asp:HyperLinkField DataNavigateUrlFields="FUserID,FUserName" SortExpression="FUserID"
DataNavigateUrlFormatString="Default2.aspx?FUserID={0}&FUserName={1}"
DataTextField="FUserID" HeaderText="用户ID" Text="用户ID" Target="_blank" />
<asp:BoundField DataField="FUserName" HeaderText="姓名" SortExpression="FUserName" />
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<asp:DropDownList ID="ddlSex" runat="server">
<asp:ListItem>男</asp:ListItem>
<asp:ListItem>女</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FUserAddress" HeaderText="家庭住址" SortExpression="FUserAddress" >
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="FUserBirthDate" DataFormatString="{0:yyyy-MM-dd}"
HeaderText="出生日期" HtmlEncode="False" SortExpression="FUserBirthDate" />
<asp:TemplateField HeaderText="起薪" SortExpression="FUserSalary">
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("FUserSalary","{0:C}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUserSalary" runat="server"
Text='<%# Bind("FUserSalary","{0:0.00}") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="查看">
<ItemTemplate>
<a href="#" onclick="javascript:varwin=window.open('Default2.aspx?FUserID=<%#Eval("FUserID")%>',null,'width=600,height=350');">查看</a>
<%--新窗口参数:
window.open (url,null,'height=600,width=350,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no');
--%>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="编辑" ShowEditButton="True" ItemStyle-Width="100"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="100" >
<HeaderStyle Width="100px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
</asp:CommandField>
<asp:CommandField HeaderText="删除" ShowDeleteButton="True" />
</Columns>
<HeaderStyle Font-Bold="True" CssClass="" BackColor="#CCCCFF" />
</asp:GridView>
</div>
<br />
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" Text="全选" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="取消" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="删除" />
<asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="True" Checked="True" oncheckedchanged="CheckBox3_CheckedChanged" Text="是否显示家庭住址" />
总金额为:<asp:Label ID="Label3" runat="server"></asp:Label>
</form>
</body>
</html>
完整后台代码Default.aspx.cs如下:
运行结果: