GridView常用操作与技巧---格式化突出显示、增删改、排序、编号、换行、对话框、翻页、求和等

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>

2HyperLinkField属性详解:

    1DataNavigateUrlFields:绑定到连接NavigateUrl属性的字段。其实就是指定,

    DataNavigateUrlFormatString所设置的URL地址后面的参数,多个参数用逗号分隔,如:FUserID,FUserName

2DataNavigateUrlFormatString:指定跳转的URL地址。如:

Default2.aspx?FUserID={0}&FUserName={1}

    3DataTextField:绑定到超链接的文本字段

    4Text:设置超链接上的文本,如果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}格式化后是1977720

    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();

    }

7GridView里的下拉列表框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="是否显示家庭住址" />   

        &nbsp;&nbsp;&nbsp;&nbsp;总金额为:<asp:Label ID="Label3" runat="server"></asp:Label>

    </form>

</body>

</html>

 

完整后台代码Default.aspx.cs如下:

 

运行结果:

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值