GridView无代码分页排序

GridView无代码分页排序
GridView选中,编辑,取消,删除
GridView正面与反面双向排序
GridView和下拉菜单DropDownList结合
GridView和CheckBox结合
鼠标移到GridView某一行时改变该行的背景象方法1
鼠标移到GridView某一行时改变该行的背景观方法2
GridView完成删除时弹出肯定对话框
GridView达成自动编号
GridView达成自定义时间货币等字符串格式
GridView完成用“…”代替超长字符串
GridView一般换行与强制换行
GridView显示隐藏某一列
GridView弹出新页面/弹出新窗口
GridView固定表头(不用javascript只用CSS,二行代码,很好用)
GridView合并表头多重表头无错完美版(以联合三列3行举例)
GridView卓绝呈现某一单元格(例如金额低于多少,分数不比格等)
GridView参预自动求和求平均值小计
GridView
数量导入Excel/Excel数据读入GridView**

 2009年5月31日下午 21:58:38

**

获取GridView中RowCommand的脚下选中央银行索引

一.GridView无代码分页排序

 <asp:GridView ID=”BookGridView” runat=”server”>

效果图:
图片 1
1.AllowSorting设为True,aspx代码中是AllowSorting=”True”;
2.暗中认可1页十条,若是要修改每页条数,修改PageSize即可,在aspx代码中是PageSize=”12″。
三.默许的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。

     <Columns>

2.GridView选中,编辑,取消,删除:

       <asp:BoundField DataField=”id” HeaderText=”图书编号” />

效果图:
图片 2

        <asp:BoundField DataField=”name” HeaderText=”图书名称” />

后台代码: 你能够应用sqlhelper,本文没用。代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

        <asp:BoundField DataField=”price” HeaderText=”单价” SortExpression=”price” />

public partial class _Default : System.Web.UI.Page 
{

        <asp:ButtonField HeaderText=”订购” Text=”放入购物车” CommandName=”AddToCart” />

//清清月儿http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=数据库名;Uid=帐号;Pwd=密码”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }

        </Columns>

//删除
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 表 where id='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }

        <PagerSettings NextPageText=”下一页” PreviousPageText=”上一页” />

//更新
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 表 set 字段1='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  </asp:GridView>

  • “‘,字段2='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()
  • “‘,字段3='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where id='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }

 

//取消
    protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }

图片 3

//绑定
    public void bind()
    {
        string sqlstr = “select * from 表”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “表”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “id” };//主键
        GridView1.DataBind();
        sqlcon.Close();
    }
}

什么样点击的”放入购物车”那一单元格,以触发RowCommond事件时取得那壹行的”图书编号”为主键

前台根本代码:                             … …
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”4″
                        ForeColor=”#333333″ GridLines=”None”
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit”>
                        <FooterStyle BackColor=”#990000″
Font-Bold=”True” ForeColor=”White” />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

后台:

三.GridView正面与反面双向排序: 效率图:点姓名各三次的排序,点其余也如出1辙能够。
图片 4图片 5
后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{

protected void
BookGridView_RowCommand(object sender,
GridViewCommandEventArgs e)

//清清月儿的博客http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证编号”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
    {
        string sPage = e.SortExpression;
        if (ViewState[“SortOrder”].ToString() == sPage)
        {
            if (ViewState[“OrderDire”].ToString() == “Desc”)
                ViewState[“OrderDire”] = “ASC”;
            else
                ViewState[“OrderDire”] = “Desc”;
        }
        else
        {
            ViewState[“SortOrder”] = e.SortExpression;
        }
        bind();
    }

    {

    public void bind()
    {
        
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        DataView view = myds.Tables[“飞狐工作室”].DefaultView;
        string sort = (string)ViewState[“SortOrder”] + ” ” +
(string)ViewState[“OrderDire”];
        view.Sort = sort;
        GridView1.DataSource = view;
        GridView1.DataBind();
        sqlcon.Close();
    }
}

        if (e.CommandName == “AddToCart”)

前台根本代码: <asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt”
OnSorting=”GridView1_Sorting” BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField DataField=”身份证编号”
HeaderText=”用户ID” SortExpression=”身份证号码” />
                            <asp:BoundField Data菲尔德=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” SortExpression=”职员和工人性别”/>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

        {

 

           //取ID的值方法1

四.GridView和下拉菜单DropDownList结合:

        GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));

效果图:
图片 6

        //此得出的值是象征那行被入选的索引值

后台代码: using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default4 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList ddl;
        if (!IsPostBack)
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“True”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 0;
                }
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“False”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 1;
                }
            }
            sqlcon.Close();
        }
    }
    public SqlDataReader ddlbind()
    {
        string sqlstr = “select distinct 职员和工人性别 from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        return sqlcom.ExecuteReader();
    }

        int id=Convert.ToInt32(GridView1.DataKeys[drv.RowIndex].Value);

前台根本代码:
<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” SortExpression=”身份证编号” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:TemplateFieldHeaderText=”员工性别”>
                                <ItemTemplate>
                                    <asp:DropDownList
ID=”DropDownList1″ runat=”server” DataSource='<%# ddlbind()%>’
DataValueField=”员工性别” DataTextField=”职员和工人性别”>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

        //此获取的值为GridView中绑定数据库中的主键值

 

        //取ID的值方法二

5.GridView和CheckBox结合:

        GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));

效果图:
图片 7

        //此得出的值是表示那行被入选的索引值

后台代码:

        //此获取的值为GridView中绑定数据库中的主键值,取值方法是选中的行中的率先列的      值,drv.RowIndex取得是选中行的目录

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

        int id = Convert.ToInt32(GridView1.Rows[drv.RowIndex].Cells[0].Text);

public partial class Default5 : System.Web.UI.Page
{
//清清月儿http://blog.csdn.net/21aspnet 
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=DongFeng贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void CheckBox2_CheckedChanged(object sender, EventArgs
e)
    {
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (CheckBox2.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (cbox.Checked == true)
            {

        //取ID的值方法叁

                string sqlstr = “delete from 飞狐工作室 where
身份证编号='” + GridView一.DataKeys[i].Value + “‘”;
                sqlcom = new SqlCommand(sqlstr, sqlcon);
                sqlcon.Open();
                sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
        }
        bind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        CheckBox2.Checked = false;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            cbox.Checked = false;
        }
    }
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “tb_Member”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证编号” };
        GridView1.DataBind();
        sqlcon.Close();
    }
}

        //因为在客户端中就曾经将LinkButton的CommandArgument与主键Id给绑定了为此在此能够一向  用e.CommandArgument得出主键ID的值

前台根本代码:

        int id = Convert.ToInt32(e.CommandArgument.ToString());

<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID=”CheckBox1″
runat=”server” />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” SortExpression=”身份证编号” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                                
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
                     <asp:CheckBox ID=”CheckBox2″ runat=”server”
AutoPostBack=”True” Font-Size=”9pt”
OnCheckedChanged=”CheckBox2_CheckedChanged”
                        Text=”全选” />
                    <asp:Button ID=”Button1″ runat=”server”
Font-Size=”9pt” Text=”取消” OnClick=”Button1_Click” />
                    <asp:Button ID=”Button2″ runat=”server”
Font-Size=”9pt” Text=”删除” OnClick=”Button2_Click” />

        //取ID的值方法四

 

        //此方法不需在模板列中装置CommandArgument的值

6.鼠标移到GridView某一行时改变该行的背景象方法一:

        string index=e.CommandArgument.ToString();
//那行被选中,取出选中行的索引

效果图:
图片 8
做法:
双击GridView的OnRowDataBound事件;
在后台的GridView一_RowDataBound()方法添加代码,最终代码如下所示:
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        int i;
        //执行循环,保障每条数据都可以立异
        for (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=’#00A9FF'”);
                //当鼠标移开时还原背景象
                e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
            }
        }

        int 
id=Convert.ToInt32(GridView1.Rows[Convert.ToInt32(index)].Cells[0].Text);
        

    }

         }

前台代码: <html xmlns=”http://www.w3.org/1999/xhtml
>
<head runat=”server”>
    <title>完成鼠标划过改变GridView的行背景象 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:GridView ID=”GridView一” runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:BoundField DataField=”身份证号码”
HeaderText=”身份证编号” ReadOnly=”True” SortExpression=”身份证编号”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址” />
                <asp:BoundField DataField=”邮政编码”
HeaderText=”邮编” SortExpression=”邮编” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource一” runat=”server”
ConnectionString=”<%$ ConnectionStrings:西风贸易ConnectionString1%>”
            SelectCommand=”SELECT top 5 [身份证号码], [姓名],
[职员和工人性别], [家中住址], [邮政编码] FROM [飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>
    
    </div>
    </form>
</body>
</html>

    }

7.鼠标移到GridView某一行时改变该行的背景观方法2:

 

效果图:
图片 9

GridView的种种用法

做法:和地方的同1便是代码差异 protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //int i;
        ////执行循环,保障每条数据都能够革新
        //for (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=’#00A9FF'”);
        //        //当鼠标移开时还原背景观
        //        e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
        //    }
        //}
        //假诺是绑定数据行 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标经过时,行背景观变 
            e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            //鼠标移出时,行背景象变 
            e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);
        }

<转自http://blog.csdn.net/hanghwp/archive/2007/04/30/1593430.aspx>

    }

GridView无代码分页排序
GridView选中,编辑,取消,删除
GridView正面与反面双向排序
GridView和下拉菜单DropDownList结合
GridView和CheckBox结合
鼠标移到GridView某一行时改变该行的背景象方法壹
鼠标移到GridView某壹行时改变该行的背景象方法二
GridView完结删除时弹出肯定对话框
GridView完结机关编号
GridView完毕自定义时间货币等字符串格式
GridView达成用“…”代替超长字符串
GridView1般换行与强制换行
GridView展现隐藏某一列
GridView弹出新页面/弹出新窗口
GridView固定表头(不用javascript只用CSS,贰行代码,很好用)
GridView合并表头多重表头无错完美版(以联合3列三行比方)
GridView优秀展现某一单元格(例如金额低于多少,分数不如格等)
GridView参加自动求和求平均值小计
GridView数据导入Excel/Excel数据读入GridView

8.GridView完成删除时弹出肯定对话框:

 

效果图:
图片 10

一.GridView无代码分页排序:

兑现情势: 双击GridView的OnRowDataBound事件;
在后台的GridView一_RowDataBound()方法添加代码,最终代码如下所示:

效果图:

    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //如若是绑定数据行 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            {
               
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你确认要刨除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            }
        }

一.AllowSorting设为True,aspx代码中是AllowSorting=”True”;
二.默许一页10条,借使要修改每页条数,修改PageSize即可,在aspx代码中是PageSize=”1二”。
叁.暗中同意的是单向排序的,右击GridView弹出“属性”,选取AllowSorting为True即可。

    }

 

9.GridView实现机关编号:

2.GridView选中,编辑,取消,删除:

效果图:
图片 11

效果图:

落到实处格局: 双击GridView的OnRowDataBound事件;
在后台的GridView一_RowDataBound()方法添加代码,最终代码如下所示:
    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //假如是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ////鼠标经过时,行背景象变 
            //e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            ////鼠标移出时,行背景观变 
            //e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);

 

            ////当有编辑列时,制止失误,要加的RowState判断 
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你肯定要刨除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

后台代码:
您能够选用sqlhelper,本文没用。代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

public partial class _Default : System.Web.UI.Page
{

    }

//清清月儿http://blog.csdn.net/21aspnet
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=数据库名;Uid=帐号;Pwd=密码”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }

 

//删除
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 表 where id='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }

注意那时最棒把前台的第一列的表头该为“编号”,因为从前的率先列被“吃掉”了。
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:Bound菲尔德 DataField=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

//更新
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 表 set 字段1='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

10.GridView完成自定义时间货币等字符串格式:

  • “‘,字段2='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim()
  • “‘,字段3='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where id='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }

效果图:
图1-未格式化前
图片 12
图2-格式化后
图片 13
消除措施:

在asp.net
二.0中,就算要在绑定列中突显比如日期格式等,如若用下边包车型客车法子是显得不断的

//取消
    protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }

<asp :BoundField DataField=”CreationDate” 
DataFormatString=”{0:M-dd-yyyy}” 
HeaderText=”CreationDate” />

//绑定
    public void bind()
    {
        string sqlstr = “select * from 表”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “表”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “id” };//主键
        GridView1.DataBind();
        sqlcon.Close();
    }
}

重中之重是出于htmlencode属性暗许设置为true,已幸免XSS攻击,安全起见而用的,所以,能够有以下三种办法化解

前台根本代码:
                            … …
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”4″
                        ForeColor=”#333333″ GridLines=”None”
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit”>
                        <FooterStyle BackColor=”#990000″
Font-Bold=”True” ForeColor=”White” />
                        <Columns>
                            <asp:Bound菲尔德 Data菲尔德=”身份证编号”
HeaderText=”用户ID” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField Data菲尔德=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField Data菲尔德=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

1、

 

<asp :GridView ID=”GridView1″ runat=”server”>
<columns>
<asp :BoundField DataField=”CreationDate” 
DataFormatString=”{0:M-dd-yyyy}” 
HtmlEncode=”false”
HeaderText=”CreationDate” />
</columns>
</asp>

三.GridView正面与反面双向排序:
功用图:点姓名各一次的排序,点其余也同等能够。

将htmlencode设置为false即可

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{

其它的消除方法为,使用模版列

//清清月儿的博客http://blog.csdn.net/21aspnet
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证号码”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
    {
        string sPage = e.SortExpression;
        if (ViewState[“SortOrder”].ToString() == sPage)
        {
            if (ViewState[“OrderDire”].ToString() == “Desc”)
                ViewState[“OrderDire”] = “ASC”;
            else
                ViewState[“OrderDire”] = “Desc”;
        }
        else
        {
            ViewState[“SortOrder”] = e.SortExpression;
        }
        bind();
    }

<asp :GridView ID=”GridView3″ runat=”server” >
<columns>
<asp :TemplateField HeaderText=”CreationDate” >
<edititemtemplate>
<asp :Label ID=”Label1″ runat=”server” 
Text='<%# Eval(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</edititemtemplate>
<itemtemplate>
<asp :Label ID=”Label1″ runat=”server” 
Text=’<%# Bind(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</itemtemplate>
</asp>
</columns>
</asp>

    public void bind()
    {
       
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        DataView view = myds.Tables[“飞狐工作室”].DefaultView;
        string sort = (string)ViewState[“SortOrder”] + ” ” +
(string)ViewState[“OrderDire”];
        view.Sort = sort;
        GridView1.DataSource = view;
        GridView1.DataBind();
        sqlcon.Close();
    }
}

前台代码: <asp:GridView ID=”GridView一” runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:BoundField DataField=”身份证号码”
HeaderText=”身份证编号” ReadOnly=”True” SortExpression=”身份证编号”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                <asp:Bound菲尔德 DataField=”出寿辰期”
HeaderText=”出出生之日期” SortExpression=”出出生之日期” />
                <asp:BoundField DataField=”起薪” HeaderText=”起薪”
SortExpression=”起薪” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource一” runat=”server”
ConnectionString=”<%$ ConnectionStrings:西风贸易ConnectionString壹%>”
            SelectCommand=”SELECT top 5 [出出生之日期], [起薪],
[身份证号码], [姓名], [家园住址], [邮政编码] FROM
[飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>

前台根本代码:
<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt”
OnSorting=”GridView1_Sorting” BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” SortExpression=”身份证编号” />
                            <asp:Bound菲尔德 DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” SortExpression=”职员和工人性别”/>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                               
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

附录-常用格式化公式: {0:C}  货币;
{0:D4}由0填充的五个字符宽的字段中显得整数;
{0:000.0}4舍5入小数点保留第四个人有效数字;
{0:N二}小数点保留多少人有效数字;{0:N贰}%   小数点保留3人有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd} 
例如2007-3-25

 

 11.GridView完结用“…”代替超长字符串:

 

效果图:
图片 14
焚薮而田办法:数据绑定后过滤每一行即可
for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv;
            string gIntro;
            if (GridView1.PageIndex == 0)
            {
                mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];//表名
                gIntro =
Convert.ToString(mydrv[“家庭住址”]);//所要处理的字段
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
            else
            {
                mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
* GridView1.PageIndex)];
                gIntro = Convert.ToString(mydrv[“家庭住址”]);
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
        } 

 

调用的方法:

四.GridView和下拉菜单DropDownList结合:

    public string SubStr(string sString, int nLeng)
    {
        if (sString.Length <= nLeng)
        {
            return sString;
        }
        string sNewStr = sString.Substring(0, nLeng);
        sNewStr = sNewStr + “…”;
        return sNewStr;
    }

效果图:

后台全体代码: using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default4 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList ddl;
        if (!IsPostBack)
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“True”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 0;
                }
                if (Convert.ToString(mydrv[“职员和工人性别”]).Trim() ==
“False”)
                {
                    ddl =
(DropDownList)GridView1.Rows[i].FindControl(“DropDownList1”);
                    ddl.SelectedIndex = 1;
                }
            }
            sqlcon.Close();
        }
    }
    public SqlDataReader ddlbind()
    {
        string sqlstr = “select distinct 职员和工人性别 from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom = new SqlCommand(sqlstr, sqlcon);
        sqlcon.Open();
        return sqlcom.ExecuteReader();
    }

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证号码”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证编号='” +
GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

前台根本代码:
<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:BoundField DataField=”身份证编号”
HeaderText=”用户ID” SortExpression=”身份证号码” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                            <asp:TemplateFieldHeaderText=”职员和工人性别”>
                                <ItemTemplate>
                                    <asp:DropDownList
ID=”DropDownList1″ runat=”server” DataSource='<%# ddlbind()%>’
DataValueField=”职员和工人性别” DataText菲尔德=”职员和工人性别”>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField Data菲尔德=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                               
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv;
                string gIntro;
                if (GridView1.PageIndex == 0)
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
                else
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
    * GridView1.PageIndex)];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
            }
            
            sqlcon.Close();
        }
        public string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + “…”;
            return sNewStr;
        }
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
            //要是是绑定数据行 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ////鼠标经过时,行背景观变 
                //e.Row.Attributes.Add(“onmouseover”,
    “this.style.backgroundColor=’#E6F5FA'”);
                ////鼠标移出时,行背景观变 
                //e.Row.Attributes.Add(“onmouseout”,
    “this.style.backgroundColor=’#FFFFFF'”);

5.GridView和CheckBox结合:

            ////当有编辑列时,制止失误,要加的RowState判断 
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你肯定要删减:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

效果图:

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

后台代码:

    }
}

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

 11.GridView一般换行与强制换行:

public partial class Default5 : System.Web.UI.Page
{
//清清月儿http://blog.csdn.net/21aspnet
    SqlConnection sqlcon;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
        }
    }
    protected void CheckBox2_CheckedChanged(object sender, EventArgs
e)
    {
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (CheckBox2.Checked == true)
            {
                cbox.Checked = true;
            }
            else
            {
                cbox.Checked = false;
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        SqlCommand sqlcom;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            if (cbox.Checked == true)
            {

效果图:
图片 15
第三设置<asp:BoundField DataField=”家庭住址” HeaderText=”家庭住址” 
ItemStyle-Width=”十0″ />
gridview里有1列绑定的多寡非常长,突显的时候在一行里面展现,页面拉得很宽。
案由是一而再英文段为二个全部导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add(“word-break”,
“break-all”)就可以。

                string sqlstr = “delete from 飞狐工作室 where
身份证号码='” + GridView一.DataKeys[i].Value + “‘”;
                sqlcom = new SqlCommand(sqlstr, sqlcon);
                sqlcon.Open();
                sqlcom.ExecuteNonQuery();
                sqlcon.Close();
            }
        }
        bind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        CheckBox2.Checked = false;
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            CheckBox cbox =
(CheckBox)GridView1.Rows[i].FindControl(“CheckBox1”);
            cbox.Checked = false;
        }
    }
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “tb_Member”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证号码” };
        GridView1.DataBind();
        sqlcon.Close();
    }
}

假使要给拥有的列扩张此属性:
 protected void Page_Load(object sender, EventArgs e)
    {
        //寻常换行
        GridView1.Attributes.Add(“style”,
“word-break:keep-all;word-wrap:normal”);
        //上面那行是全自动换行
        GridView1.Attributes.Add(“style”,
“word-break:break-all;word-wrap:break-word”);
        if (!IsPostBack)
        {
             bind();//调用数据绑定即可
        }
    }
总之:善用CSS的word-break:break-all;word-wrap:break-word属性即可,那一个性格是通用的对于安常习故的南换行难题都得以消除,不囿于于GridView。

前台根本代码:

 12.GridView显示隐藏某一列: 本方案为月儿独辟蹊径,分歧于网上其余办法,笔者认为用叁个Check博克斯更人性化,那样能够隐蔽不须要的列,让用户自个儿挑选须求出现的列,在处理多列时这是叁个很好的消除方案!

<asp:GridView ID=”GridView1″ runat=”server” AllowSorting=”True”
AutoGenerateColumns=”False”
                        CellPadding=”3″ Font-Size=”9pt” 
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                             <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:CheckBox ID=”CheckBox1″
runat=”server” />
                                </ItemTemplate>
                            </asp:TemplateField>
                             <asp:BoundField DataField=”身份证号码”
HeaderText=”用户ID” SortExpression=”身份证编号” />
                            <asp:Bound菲尔德 DataField=”姓名”
HeaderText=”用户姓名” SortExpression=”姓名”/>
                           
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址”/>
                               
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
                     <asp:CheckBox ID=”CheckBox2″ runat=”server”
AutoPostBack=”True” Font-Size=”9pt”
OnCheckedChanged=”CheckBox2_CheckedChanged”
                        Text=”全选” />
                    <asp:Button ID=”Button1″ runat=”server”
Font-Size=”9pt” Text=”取消” OnClick=”Button1_Click” />
                    <asp:Button ID=”Button2″ runat=”server”
Font-Size=”9pt” Text=”删除” OnClick=”Button2_Click” />

效果图:
图1-开始
图片 16
图二-点击显示的CheckBox后
图片 17

陆.鼠标移到GridView某一行时改变该行的背景象方法一:

消除方案: public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证号码” };
        GridView1.DataBind();
        sqlcon.Close();
        GridView1.Columns[3].Visible = false;//一起头东躲江苏
        Check博克斯一.Checked = false;//要是不那样前边的代码会把他True

    }

效果图:

双击CheckBox一,在CheckedChanged方法里写上代码,最后代码如下:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
         GridView1.Columns[3].Visible=!
GridView1.Columns[3].Visible;
        
Response.Write(“GridView壹的第陆列今后的显示隐藏状态是:”+GridView1.Columns[3].Visible.ToString());
    }

做法:
双击GridView的OnRowDataBound事件;
在后台的GridView壹_RowDataBound()方法添加代码,最终代码如下所示:
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        int i;
        //执行循环,保障每条数据都足以立异
        for (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=’#00A9FF'”);
                //当鼠标移开时还原背景观
                e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
            }
        }

注意:CheckBox1的AutoPostBack要True!

    }

后台全体代码如下:

前台代码:
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>完毕鼠标划过改变GridView的行背景观清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:GridView ID=”GridView一” runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:BoundField DataField=”身份证号码”
HeaderText=”身份证编号” ReadOnly=”True” SortExpression=”身份证编号”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” SortExpression=”家庭住址” />
                <asp:BoundField Data菲尔德=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource壹” runat=”server”
ConnectionString=”<%$ ConnectionStrings:西风贸易ConnectionString壹%>”
            SelectCommand=”SELECT top 5 [身份证号码], [姓名],
[职工性别], [家园住址], [邮编] FROM [飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

七.鼠标移到GridView某一行时改变该行的背景象方法贰:

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom; 
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证编号”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
                   }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证编号='” +
GridView一.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

效果图:

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
            GridView1.Columns[3].Visible = false;
            CheckBox1.Checked = false;
        }
        protected void CheckBox1_CheckedChanged(object sender, EventArgs
    e)
        {
             GridView1.Columns[3].Visible=!
    GridView1.Columns[3].Visible;
            
    Response.Write(“GridView1的第四列今后的显得隐藏状态是:”+GridView一.Columns[3].Visible.ToString());
        }
    }

做法:和地点的壹致便是代码差异
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //int i;
        ////执行循环,保险每条数据都能够立异
        //for (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=’#00A9FF'”);
        //        //当鼠标移开时还原背景象
        //        e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=c”);
        //    }
        //}
        //假如是绑定数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //鼠标经过时,行背景观变
            e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            //鼠标移出时,行背景色变
            e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);
        }

前台代码: <!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>GridView彰显隐藏列 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div>
                   <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”邮政编码”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:CheckBox ID=”CheckBox1″ runat=”server”
AutoPostBack=”True” Font-Size=”12px”
            OnCheckedChanged=”CheckBox1_CheckedChanged”
Text=”突显隐藏家庭住址” /></div>
    </form>
</body>
</html>

 

 13.GridView弹出新页面/弹出制定大小地方新窗口:

 

效果图:
图片 18

 

方案一:简单的法子,新窗口不固定大小
 <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:Bound菲尔德 DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:HyperLinkField HeaderText=”姓名”
Text=”姓名” DataNavigateUrlFields=”姓名”
DataNavigateUrlFormatString=”Default6.aspx?GoodsID={0}”
Target=”mainframe” NavigateUrl=”~/Default6.aspx” DataTextField=”姓名”
>
                    </asp:HyperLinkField>
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
DataNavigateUrlFields是链接的字段名,DataNavigateUrlFormatString是路线。

八.GridView落到实处删除时弹出肯定对话框:

方案二:精确控制弹出窗口大小地点
<asp:HyperLinkColumn DataNavigateUrlField=”EmployeeID”
DataNavigateUrlFormatString=”javascript:varwin=window.open(‘detail.aspx?ID={0}’,null,’width=300,height=200′);window.Close();”
       DataTextField=”LastName”
HeaderText=”LastName”></asp:HyperLinkColumn>

效果图:

选用的是整合javascript的window.open方法,关于window.open的参数网上有成都百货上千帖子,本站也有为数不少参照
弹出窗口大全 http://blog.csdn.net/21aspnet/archive/2004/10/25/150231.aspx  
即可!

完成形式:
双击GridView的OnRowDataBound事件;
在后台的GridView壹_RowDataBound()方法添加代码,最终代码如下所示:

  14.GridView固定表头(不用javascript只用CSS!,很好用):

    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //借使是绑定数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
             if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            {
               
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你确认要去除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            }
        }

效果图:
图片 19

    }

代码: <!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>GridView固定表头 清清月儿http://blog.csdn.net/21aspnet </title>
        <style> 
.Freezing 
   { 
    
   position:relative ; 
   table-layout:fixed;
   top:expression(this.offsetParent.scrollTop);   
   z-index: 10;
   }

玖.GridView落到实处自动编号:

.Freezing
th{text-overflow:ellipsis;overflow:hidden;white-space:
nowrap;padding:2px;}
</style> 
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div style=”overflow-y: scroll; height: 200px;width:300px”
id=”dvBody”>
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:Bound菲尔德 Data菲尔德=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” CssClass=”Freezing”/>
                    </asp:GridView>
        </div>

效果图:

    </form>
</body>
</html>

贯彻格局:
双击GridView的OnRowDataBound事件;
在后台的GridView一_RowDataBound()方法添加代码,最后代码如下所示:
    protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        //如若是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ////鼠标经过时,行背景观变
            //e.Row.Attributes.Add(“onmouseover”,
“this.style.backgroundColor=’#E6F5FA'”);
            ////鼠标移出时,行背景观变
            //e.Row.Attributes.Add(“onmouseout”,
“this.style.backgroundColor=’#FFFFFF'”);

用法:CSS设如上的体制,HeaderStyle加CssClass=”Freezing,套住GridView的Div设置中度小幅度<div style=”overflow-y: scroll; height: 200px;width:200px” >

            ////当有编辑列时,幸免失误,要加的RowState判断
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你确认要刨除:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

15.GridView合并表头多重表头无错完美版(以联合三列三行比喻)

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

效果图:
图片 20

    }


后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
public partial class _Default : System.Web.UI.Page 
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
            
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

 

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='” 
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
        }

留神那时最棒把前台的率先列的表头该为“编号”,因为从前的第一列被“吃掉”了。
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”>
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”职员和工人性别”
HeaderText=”性别” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址” />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>

//这里就是消除方案     protected void
GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                //第贰行表头
                TableCellCollection tcHeader = e.Row.Cells;
                tcHeader.Clear();
                tcHeader.Add(new TableHeaderCell());
                tcHeader[0].Attributes.Add(“rowspan”, “3”); //跨Row
                tcHeader[0].Attributes.Add(“bgcolor”, “white”);
                tcHeader[0].Text = “”;
                tcHeader.Add(new TableHeaderCell());
                //tcHeader[1].Attributes.Add(“bgcolor”, “Red”);
                tcHeader[1].Attributes.Add(“colspan”,
“6”); //跨Column
                tcHeader[1].Text =
“全体音讯</th></tr><tr>”;

十.GridView达成自定义时间货币等字符串格式:

                //第3行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[2].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[2].Text = “身份证编号”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[3].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[3].Attributes.Add(“colspan”, “2”);
                tcHeader[3].Text = “基本音讯”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[4].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[4].Text = “福利”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[5].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[5].Attributes.Add(“colspan”, “2”);
                tcHeader[5].Text =
“联系形式</th></tr><tr>”;

效果图:
图一-未格式化前

                //第1行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[6].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[6].Text = “身份证编号”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[7].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[7].Text = “姓名”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[8].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[8].Text = “出破壳日期”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[9].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[9].Text = “薪水”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[10].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[10].Text = “家庭住址”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[11].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[11].Text = “邮编”;
                break;
        }
    }
}

图二-格式化后

前台:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

竭泽而渔办法:
在asp.net
贰.0中,假使要在绑定列中展现比如日期格式等,假设用下边包车型大巴艺术是显得不断的

<html xmlns=”http://www.w3.org/1999/xhtml
>
<head runat=”server”>
    <title>GridView合并多重表头表头 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:Bound菲尔德 DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

<asp :BoundField DataField=”CreationDate”
DataFormatString=”{0:M-dd-yyyy}”
HeaderText=”CreationDate” />

    </form>
</body>
</html>

器重是由于htmlencode属性暗许设置为true,已防止XSS攻击,安全起见而用的,所以,能够有以下二种方法消除

16.GridView特出突显某1单元格(例如金额低于多少,分数比不上格等)

1、

效果图:
图片 21

<asp :GridView ID=”GridView1″ runat=”server”>
<columns>
<asp :BoundField DataField=”CreationDate”
DataFormatString=”{0:M-dd-yyyy}”
HtmlEncode=”false”
HeaderText=”CreationDate” />
</columns>
</asp>

消除方案:重倘若绑定后过滤  GridView1.DataBind();
        for (int i = 0; i <=
GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
            string score = Convert.ToString(mydrv[“起薪”]);
            if (Convert.ToDouble(score) <
342九七.00)//我们那里依据具体情形设置可能ToInt3二之类
            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();

将htmlencode设置为false即可

整套后台代码:

除此以外的缓解办法为,使用模版列

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;

<asp :GridView ID=”GridView3″ runat=”server” >
<columns>
<asp :TemplateField HeaderText=”CreationDate” >
<edititemtemplate>
<asp :Label ID=”Label1″ runat=”server”
Text='<%# Eval(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</edititemtemplate>
<itemtemplate>
<asp :Label ID=”Label1″ runat=”server”
Text=’<%# Bind(“CreationDate”, “{0:M-dd-yyyy}”) %>’>
</asp>
</itemtemplate>
</asp>
</columns>
</asp>

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

前台代码:
<asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” DataKeyNames=”身份证号码”
            DataSourceID=”SqlDataSource1″ AllowSorting=”True”
BackColor=”White” BorderColor=”#CCCCCC” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ Font-Size=”12px”
OnRowDataBound=”GridView1_RowDataBound”>
            <Columns>
                <asp:Bound菲尔德 Data菲尔德=”身份证号码”
HeaderText=”身份证号码” ReadOnly=”True” SortExpression=”身份证编号”
/>
                <asp:BoundField DataField=”姓名” HeaderText=”姓名”
SortExpression=”姓名” />
                <asp:Bound菲尔德 DataField=”邮政编码”
HeaderText=”邮政编码” SortExpression=”邮编” />
                <asp:BoundField DataField=”出生日期”
HeaderText=”出破壳日期” SortExpression=”出诞辰期” />
                <asp:BoundField DataField=”起薪” HeaderText=”起薪”
SortExpression=”起薪” />
            </Columns>
            <FooterStyle BackColor=”White” ForeColor=”#000066″
/>
            <RowStyle ForeColor=”#000066″ />
            <SelectedRowStyle BackColor=”#669999″ Font-Bold=”True”
ForeColor=”White” />
            <PagerStyle BackColor=”White” ForeColor=”#000066″
HorizontalAlign=”Left” />
            <HeaderStyle BackColor=”#006699″ Font-Bold=”True”
ForeColor=”White” />
        </asp:GridView>
        <asp:SqlDataSource ID=”SqlDataSource一” runat=”server”
ConnectionString=”<%$ ConnectionStrings:西风贸易ConnectionString1%>”
            SelectCommand=”SELECT top 5 [出出生之日期], [起薪],
[身份证号码], [姓名], [家园住址], [邮编] FROM
[飞狐工作室]”
DataSourceMode=”DataReader”></asp:SqlDataSource>

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

附录-常用格式化公式:
{0:C}  货币;
{0:D四}由0填充的五个字符宽的字段中浮现整数;
{0:000.0}四舍5入小数点保留第肆个人有效数字;
{0:N二}小数点保留4个人有效数字;{0:N2}%   小数点保留2个人有效数字加百分号;
{0:D}长日期;{0:d}短日期;{0:yy-MM-dd}   例如07-3-25;;{0:yyyy-MM-dd} 
例如2007-3-25

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            for (int i = 0; i <=
    GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
    myds.Tables[“飞狐工作室”].DefaultView[i];
                string score = Convert.ToString(mydrv[“起薪”]);
                if (Convert.ToDouble(score) < 34297.00)//我们那里依据具体情况设置恐怕ToInt3二等等

 

            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();
    }
}

 11.GridView兑现用“…”代替超长字符串:

前台代码:

效果图:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

焚林而猎办法:数据绑定后过滤每一行即可
for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv;
            string gIntro;
            if (GridView1.PageIndex == 0)
            {
                mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];//表名
                gIntro =
Convert.ToString(mydrv[“家庭住址”]);//所要处理的字段
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
            else
            {
                mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
* GridView1.PageIndex)];
                gIntro = Convert.ToString(mydrv[“家庭住址”]);
                GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
2);
            }
        }

<html xmlns=”http://www.w3.org/1999/xhtml
>
<head id=”Head1″ runat=”server”>
    <title>GridView卓越显示某1单元格 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  DataFormatString=”{0:C}” HtmlEncode=”false”/>
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮政编码” />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

调用的办法:

    </form>
</body>
</html>

    public string SubStr(string sString, int nLeng)
    {
        if (sString.Length <= nLeng)
        {
            return sString;
        }
        string sNewStr = sString.Substring(0, nLeng);
        sNewStr = sNewStr + “…”;
        return sNewStr;
    }

 17.GridView加入自动求和求平均值小计

后台全体代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

效果图:图片 22
消除方案:    
private double sum =
0;//取钦定列的数额和,你要依据具体情形对待可能你要拍卖的是int
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
        
        if (e.Row.RowIndex >= 0)
        {
            sum += Convert.ToDouble(e.Row.Cells[6].Text);
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[5].Text = “总报酬为:”;
            e.Row.Cells[6].Text = sum.ToString();
            e.Row.Cells[3].Text = “平均报酬为:”;
            e.Row.Cells[4].Text = ((int)(sum /
GridView1.Rows.Count)).ToString();
            
        }
    }

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证编号”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证号码='” +
GridView一.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

后台全体代码: using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv;
                string gIntro;
                if (GridView1.PageIndex == 0)
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
                else
                {
                    mydrv = myds.Tables[“飞狐工作室”].DefaultView[i + (5
    * GridView1.PageIndex)];
                    gIntro = Convert.ToString(mydrv[“家庭住址”]);
                    GridView1.Rows[i].Cells[3].Text = SubStr(gIntro,
    2);
                }
            }
           
            sqlcon.Close();
        }
        public string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + “…”;
            return sNewStr;
        }
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
            //假诺是绑定数据行
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ////鼠标经过时,行背景象变
                //e.Row.Attributes.Add(“onmouseover”,
    “this.style.backgroundColor=’#E6F5FA'”);
                ////鼠标移出时,行背景象变
                //e.Row.Attributes.Add(“onmouseout”,
    “this.style.backgroundColor=’#FFFFFF'”);

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

            ////当有编辑列时,幸免失误,要加的RowState判断
            //if (e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate)
            //{
            //   
((LinkButton)e.Row.Cells[6].Controls[0]).Attributes.Add(“onclick”,
“javascript:return confirm(‘你认可要删减:\”” + e.Row.Cells[1].Text +
“\”吗?’)”);
            //}

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
        }
        private double sum = 0;//取钦命列的数码和
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
            
            if (e.Row.RowIndex >= 0)
            {
                sum += Convert.ToDouble(e.Row.Cells[6].Text);
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[5].Text = “总薪金为:”;
                e.Row.Cells[6].Text = sum.ToString();
                e.Row.Cells[3].Text = “平均薪资为:”;
                e.Row.Cells[4].Text = ((int)(sum /
    GridView1.Rows.Count)).ToString();
                
            }
        }
    }
    前台:唯一的花样就是设置ShowFooter=”True” ,不然暗中认可表头为隐藏的!
    <asp:GridView ID=”GridView1″ runat=”server”   
    AutoGenerateColumns=”False” CellPadding=”3″ 
    OnRowEditing=”GridView1_RowEditing”
                            OnRowUpdating=”GridView1_RowUpdating”
    OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
    BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
    Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”
    ShowFooter=”True”  >
                            <FooterStyle BackColor=”White”
    ForeColor=”#000066″ />
                            <Columns>
                                <asp:CommandField HeaderText=”编辑”
    ShowEditButton=”True” />
                                <asp:BoundField DataField=”身份证号码”
    HeaderText=”编号” ReadOnly=”True” />
                                <asp:BoundField DataField=”姓名”
    HeaderText=”姓名”  />
                                <asp:BoundField DataField=”出出生之日期”
    HeaderText=”邮政编码”  />
                                <asp:BoundField Data菲尔德=”家庭住址”
    HeaderText=”家庭住址”  />
                                <asp:BoundField DataField=”邮政编码”
    HeaderText=”邮编” />
                                <asp:BoundField DataField=”起薪”
    HeaderText=”起薪”  />
                               
                            </Columns>
                            <RowStyle ForeColor=”#000066″ />
                            <SelectedRowStyle BackColor=”#669999″
    Font-Bold=”True” ForeColor=”White” />
                            <PagerStyle BackColor=”White”
    ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
    DataGridFixedHeader”/>
                            <HeaderStyle BackColor=”#006699″
    Font-Bold=”True” ForeColor=”White” />
                        </asp:GridView>

    }
}

 

 

 18.GridView**多少导入Excel/Excel数据读入GridView**

 

效果图: 图片 23

 1一.GridView相似换行与强制换行:

化解方案:
页面增添3个按钮,单击事件添加如下方法:
protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生战绩报表.xls”);
    }

效果图:

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
//假设未有上边方法会报错连串“GridView”的控件“GridView1”必须放在具有
runat=server 的窗体标记内
    public override void VerifyRenderingInServerForm(Control
control)
    {
    }
再有由于是文件操作所以要引进名称空间IO和Text

先是设置<asp:Bound菲尔德 Data菲尔德=”家庭住址” HeaderText=”家庭住址” 
ItemStyle-Width=”⑩0″ />
gridview里有1列绑定的数量不长,展现的时候在壹行里面展现,页面拉得很宽。
原因是接二连三英文段为1个完完全全导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add(“word-break”,
“break-all”)就可以。

后台代码: using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

只要要给全部的列扩张此属性:
 protected void Page_Load(object sender, EventArgs e)
    {
        //平常换行
        GridView1.Attributes.Add(“style”,
“word-break:keep-all;word-wrap:normal”);
        //上面这行是电动换行
        GridView1.Attributes.Add(“style”,
“word-break:break-all;word-wrap:break-word”);
        if (!IsPostBack)
        {
             bind();//调用数据绑定即可
        }
    }
简单来说:善用CSS的word-break:break-all;word-wrap:break-word属性即可,这几个天性是通用的对于执迷不悟的南换行难题都足以缓解,不囿于于GridView。

        }
    }
    
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证号码” };
        GridView1.DataBind();
        sqlcon.Close();
    }

 1二.GridView呈现隐藏某1列:
本方案为月球独创,不一样于网上别的方法,作者觉得用3个CheckBox更人性化,那样能够隐蔽不须要的列,让用户自个儿挑选须求出现的列,在拍卖多列时那是1个很好的化解方案!

    protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生成绩报表.xls”);
    }

效果图:
图1-开始

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
    
}

图二-点击彰显的CheckBox后

前台
<asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″  
                         BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px” Font-Size=”12px”   >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” />
                            <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:Button ID=”Button1″ runat=”server”
OnClick=”Button1_Click” Text=”导出” />

消除方案:
public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证号码” };
        GridView1.DataBind();
        sqlcon.Close();
        GridView1.Columns[3].Visible = false;//一初叶东躲甘肃
        Check博克斯1.Checked = false;//假若不那样前面包车型大巴代码会把她True
    }

读取Excel数据的代码:这一个很简单的
private DataSet CreateDataSource()
    {
        string strCon;
        strCon = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” +
Server.MapPath(“excel.xls”) + “; Extended Properties=Excel 8.0;”;
        OleDbConnection olecon = new OleDbConnection(strCon);
        OleDbDataAdapter myda = new OleDbDataAdapter(“SELECT * FROM
[Sheet1$]”, strCon);
        DataSet myds = new DataSet();
        myda.Fill(myds);
        return myds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();
    }

双击Check博克斯一,在CheckedChanged方法里写上代码,最终代码如下:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {
         GridView1.Columns[3].Visible=!
GridView1.Columns[3].Visible;
        
Response.Write(“GridView1的第肆列未来的显示隐藏状态是:”+GridView一.Columns[3].Visible.ToString());
    }

注意:CheckBox1的AutoPostBack要True!

后台全体代码如下:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=西风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState[“SortOrder”] = “身份证编号”;
            ViewState[“OrderDire”] = “ASC”;
            bind();
                   }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowDeleting(object sender,
GridViewDeleteEventArgs e)
    {
        string sqlstr = “delete from 飞狐工作室 where 身份证编号='” +
GridView一.DataKeys[e.RowIndex].Value.ToString() + “‘”;
        sqlcon = new SqlConnection(strCon);
        sqlcom = new SqlCommand(sqlstr,sqlcon);
        sqlcon.Open();
        sqlcom.ExecuteNonQuery();
        sqlcon.Close();
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
            GridView1.Columns[3].Visible = false;
            CheckBox1.Checked = false;
        }
        protected void CheckBox1_CheckedChanged(object sender, EventArgs
    e)
        {
             GridView1.Columns[3].Visible=!
    GridView1.Columns[3].Visible;
            
    Response.Write(“GridView一的第4列现在的显得隐藏状态是:”+GridView一.Columns[3].Visible.ToString());
        }
    }

前台代码:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>GridView呈现隐藏列
清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div>
                   <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:Bound菲尔德 DataField=”姓名”
HeaderText=”用户姓名” />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:CheckBox ID=”CheckBox1″ runat=”server”
AutoPostBack=”True” Font-Size=”12px”
            OnCheckedChanged=”CheckBox1_CheckedChanged”
Text=”显示隐藏家庭住址” /></div>
    </form>
</body>
</html>

 1三.GridView弹出新页面/弹出制定大小地点新窗口:

效果图:

方案1:简单的法子,新窗口不定点大小
 <asp:GridView ID=”GridView1″ runat=”server”
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮编” />
                            <asp:Bound菲尔德 DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:HyperLinkField HeaderText=”姓名”
Text=”姓名” DataNavigateUrlFields=”姓名”
DataNavigateUrlFormatString=”Default6.aspx?GoodsID={0}”
Target=”mainframe” NavigateUrl=”~/Default6.aspx” DataTextField=”姓名”
>
                    </asp:HyperLinkField>
                            <asp:CommandField HeaderText=”选择”
ShowSelectButton=”True” />
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:CommandField HeaderText=”删除”
ShowDeleteButton=”True” />
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left” />
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
DataNavigateUrlFields是链接的字段名,DataNavigateUrlFormatString是路线。

方案二:精确控制弹出窗口大小地点
<asp:HyperLinkColumn DataNavigateUrlField=”EmployeeID”
DataNavigateUrlFormatString=”javascript:varwin=window.open(‘detail.aspx?ID={0}’,null,’width=300,height=200′);window.Close();”
       DataTextField=”LastName”
HeaderText=”LastName”></asp:HyperLinkColumn>

利用的是整合javascript的window.open方法,关于window.open的参数网上有好多帖子,本站也有广大参阅
弹出窗口大全
http://blog.csdn.net/21aspnet/archive/2004/10/25/150231.aspx   即可!

 

 

 

  1肆.GridView永恒表头(不用javascript只用CSS!,很好用):

效果图:

代码:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>GridView固定表头 清清月儿http://blog.csdn.net/21aspnet
</title>
        <style>
.Freezing
   {
   
   position:relative ;
   table-layout:fixed;
   top:expression(this.offsetParent.scrollTop);  
   z-index: 10;
   }

.Freezing th{text-overflow:ellipsis;overflow:hidden;white-space:
nowrap;padding:2px;}
</style>
</head>
<body style=”font-size=12px”>
    <form id=”form1″ runat=”server”>
    <div style=”overflow-y: scroll; height: 200px;width:300px”
id=”dvBody”>
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″
OnRowDeleting=”GridView1_RowDeleting”
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” SortExpression=”邮政编码” />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                           
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” CssClass=”Freezing”/>
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

用法:CSS设如上的样式,HeaderStyle加CssClass=”Freezing,套住GridView的Div设置中度小幅度<div style=”overflow-y: scroll; height: 200px;width:200px” >

1伍.GridView合并表头多重表头无错完美版(以统一三列③行比喻)

效果图:

 

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=南风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
           
        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom=new SqlCommand(sqlstr,sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证号码” };
            GridView1.DataBind();
            sqlcon.Close();
        }

//那里正是涸泽而渔方案
    protected void GridView1_RowCreated(object sender,
GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                //第一行表头
                TableCellCollection tcHeader = e.Row.Cells;
                tcHeader.Clear();
                tcHeader.Add(new TableHeaderCell());
                tcHeader[0].Attributes.Add(“rowspan”, “3”); //跨Row
                tcHeader[0].Attributes.Add(“bgcolor”, “white”);
                tcHeader[0].Text = “”;
                tcHeader.Add(new TableHeaderCell());
                //tcHeader[1].Attributes.Add(“bgcolor”, “Red”);
                tcHeader[1].Attributes.Add(“colspan”, “6”);
//跨Column
                tcHeader[1].Text =
“整体新闻</th></tr><tr>”;

                //第3行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[2].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[2].Text = “身份证号码”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[3].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[3].Attributes.Add(“colspan”, “2”);
                tcHeader[3].Text = “基本音讯”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[4].Attributes.Add(“bgcolor”,
“DarkSeaGreen”);
                tcHeader[4].Text = “福利”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[5].Attributes.Add(“bgcolor”,
“LightSteelBlue”);
                tcHeader[5].Attributes.Add(“colspan”, “2”);
                tcHeader[5].Text =
“联系格局</th></tr><tr>”;

                //第1行表头
                tcHeader.Add(new TableHeaderCell());
                tcHeader[6].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[6].Text = “身份证号码”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[7].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[7].Text = “姓名”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[8].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[8].Text = “出生日期”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[9].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[9].Text = “薪水”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[10].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[10].Text = “家庭住址”;
                tcHeader.Add(new TableHeaderCell());
                tcHeader[11].Attributes.Add(“bgcolor”, “Khaki”);
                tcHeader[11].Text = “邮编”;
                break;
        }
    }
}

前台:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>GridView合并多重表头表头
清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px” OnRowCreated=”GridView1_RowCreated”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮编”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮编”
HeaderText=”邮编” />
                          
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

1六.GridView优良呈现某1单元格(例如金额低于多少,分数比不上格等)

效果图:

 

焚薮而田方案:主假如绑定后过滤
 GridView1.DataBind();
        for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
        {
            DataRowView mydrv =
myds.Tables[“飞狐工作室”].DefaultView[i];
            string score = Convert.ToString(mydrv[“起薪”]);
            if (Convert.ToDouble(score) <
342九7.00)//大家那里依照具体景况设置恐怕ToInt3二等等
            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();

全部后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证号码='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 10 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            for (int i = 0; i <= GridView1.Rows.Count – 1; i++)
            {
                DataRowView mydrv =
    myds.Tables[“飞狐工作室”].DefaultView[i];
                string score = Convert.ToString(mydrv[“起薪”]);
                if (Convert.ToDouble(score) <
    34297.00)//大家那里依照具体意况设置也许ToInt32之类

            {
                GridView1.Rows[i].Cells[4].BackColor =
System.Drawing.Color.Red;
            }
        }
        sqlcon.Close();
    }
}

前台代码:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1″ runat=”server”>
    <title>GridView优秀显示某壹单元格
清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
    <form id=”form1″ runat=”server”>
    <div  >
                   <asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
OnRowEditing=”GridView1_RowEditing”
                        OnRowUpdating=”GridView1_RowUpdating”
OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
Font-Size=”12px”  >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:CommandField HeaderText=”编辑”
ShowEditButton=”True” />
                            <asp:BoundField DataField=”身份证号码”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField Data菲尔德=”出出生之日期”
HeaderText=”邮编”  />
                             <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  DataFormatString=”{0:C}” HtmlEncode=”false”/>
                            <asp:Bound菲尔德 DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮政编码”
HeaderText=”邮编” />
                          
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        </div>

    </form>
</body>
</html>

 一7.GridView参与自动求和求平均值小计

效果图:
杀鸡取卵方案:   
private double sum =
0;//取钦赐列的数目和,你要基于具体情状对待只怕你要处理的是int
protected void GridView1_RowDataBound(object sender,
GridViewRowEventArgs e)
    {
       
        if (e.Row.RowIndex >= 0)
        {
            sum += Convert.ToDouble(e.Row.Cells[6].Text);
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[5].Text = “总薪资为:”;
            e.Row.Cells[6].Text = sum.ToString();
            e.Row.Cells[3].Text = “平均报酬为:”;
            e.Row.Cells[4].Text = ((int)(sum /
GridView1.Rows.Count)).ToString();
           
        }
    }

后台全体代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;

public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
    protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
    }
    protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
    {
        sqlcon = new SqlConnection(strCon);
        string sqlstr = “update 飞狐工作室 set 姓名='”
            +
((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim()

  • “‘,家庭住址='”
                +
    ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim()
  • “‘ where 身份证编号='”
                + GridView1.DataKeys[e.RowIndex].Value.ToString() + “‘”;
            sqlcom = new SqlCommand(sqlstr, sqlcon);
            sqlcon.Open();
            sqlcom.ExecuteNonQuery();
            sqlcon.Close();
            GridView1.EditIndex = -1;
            bind();
        }
        protected void GridView1_RowCancelingEdit(object sender,
    GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            bind();
        }
        public void bind()
        {
            string sqlstr = “select top 5 * from 飞狐工作室”;
            sqlcon = new SqlConnection(strCon);
            SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
            DataSet myds = new DataSet();
            sqlcon.Open();
            myda.Fill(myds, “飞狐工作室”);
            GridView1.DataSource = myds;
            GridView1.DataKeyNames = new string[] { “身份证编号” };
            GridView1.DataBind();
            sqlcon.Close();
        }
        private double sum = 0;//取钦点列的数据和
        protected void GridView1_RowDataBound(object sender,
    GridViewRowEventArgs e)
        {
           
            if (e.Row.RowIndex >= 0)
            {
                sum += Convert.ToDouble(e.Row.Cells[6].Text);
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[5].Text = “总薪俸为:”;
                e.Row.Cells[6].Text = sum.ToString();
                e.Row.Cells[3].Text = “平均薪资为:”;
                e.Row.Cells[4].Text = ((int)(sum /
    GridView1.Rows.Count)).ToString();
               
            }
        }
    }
    前台:唯1的花头就是安装ShowFooter=”True” ,不然暗中认可表头为隐蔽的!
    <asp:GridView ID=”GridView1″ runat=”server”   
    AutoGenerateColumns=”False” CellPadding=”3″ 
    OnRowEditing=”GridView1_RowEditing”
                            OnRowUpdating=”GridView1_RowUpdating”
    OnRowCancelingEdit=”GridView1_RowCancelingEdit” BackColor=”White”
    BorderColor=”#CCCCCC” BorderStyle=”None” BorderWidth=”1px”
    Font-Size=”12px” OnRowDataBound=”GridView1_RowDataBound”
    ShowFooter=”True”  >
                            <FooterStyle BackColor=”White”
    ForeColor=”#000066″ />
                            <Columns>
                                <asp:CommandField HeaderText=”编辑”
    ShowEditButton=”True” />
                                <asp:BoundField DataField=”身份证编号”
    HeaderText=”编号” ReadOnly=”True” />
                                <asp:BoundField DataField=”姓名”
    HeaderText=”姓名”  />
                                <asp:BoundField DataField=”出出生之日期”
    HeaderText=”邮编”  />
                                <asp:BoundField DataField=”家庭住址”
    HeaderText=”家庭住址”  />
                                <asp:BoundField DataField=”邮编”
    HeaderText=”邮编” />
                                <asp:BoundField DataField=”起薪”
    HeaderText=”起薪”  />
                              
                            </Columns>
                            <RowStyle ForeColor=”#000066″ />
                            <SelectedRowStyle BackColor=”#669999″
    Font-Bold=”True” ForeColor=”White” />
                            <PagerStyle BackColor=”White”
    ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
    DataGridFixedHeader”/>
                            <HeaderStyle BackColor=”#006699″
    Font-Bold=”True” ForeColor=”White” />
                        </asp:GridView>

 

 1八.GridView多少导入Excel/Excel数据读入GridView

效果图:

解决方案:
页面增添2个按钮,单击事件添加如下方法:
protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生成绩报表.xls”);
    }

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
//假若未有上面方法会报错类型“GridView”的控件“GridView1”必须放在具有
runat=server 的窗体标记内
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
还有由于是文本操作所以要引进名称空间IO和Text

后台代码:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
public partial class Default7 : System.Web.UI.Page
{
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    string strCon = “Data
Source=(local);Database=东风贸易;Uid=sa;Pwd=sa”;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();

        }
    }
   
    public void bind()
    {
        string sqlstr = “select top 5 * from 飞狐工作室”;
        sqlcon = new SqlConnection(strCon);
        SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
        DataSet myds = new DataSet();
        sqlcon.Open();
        myda.Fill(myds, “飞狐工作室”);
        GridView1.DataSource = myds;
        GridView1.DataKeyNames = new string[] { “身份证号码” };
        GridView1.DataBind();
        sqlcon.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Export(“application/ms-excel”, “学生成绩报表.xls”);
    }

    private void Export(string FileType, string FileName)
    {
        Response.Charset = “GB2312”;
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.AppendHeader(“Content-Disposition”,
“attachment;filename=” + HttpUtility.UrlEncode(FileName,
Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        GridView1.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
   
}

前台:
<asp:GridView ID=”GridView1″ runat=”server”   
AutoGenerateColumns=”False” CellPadding=”3″ 
                         BackColor=”White” BorderColor=”#CCCCCC”
BorderStyle=”None” BorderWidth=”1px” Font-Size=”12px”   >
                        <FooterStyle BackColor=”White”
ForeColor=”#000066″ />
                        <Columns>
                            <asp:BoundField DataField=”身份证编号”
HeaderText=”编号” ReadOnly=”True” />
                            <asp:BoundField DataField=”姓名”
HeaderText=”姓名”  />
                            <asp:BoundField DataField=”出生日期”
HeaderText=”邮政编码”  />
                            <asp:BoundField DataField=”家庭住址”
HeaderText=”家庭住址”  />
                            <asp:BoundField DataField=”邮政编码”
HeaderText=”邮编” />
                            <asp:BoundField DataField=”起薪”
HeaderText=”起薪”  />
                          
                        </Columns>
                        <RowStyle ForeColor=”#000066″ />
                        <SelectedRowStyle BackColor=”#669999″
Font-Bold=”True” ForeColor=”White” />
                        <PagerStyle BackColor=”White”
ForeColor=”#000066″ HorizontalAlign=”Left”  CssClass=”ms-formlabel
DataGridFixedHeader”/>
                        <HeaderStyle BackColor=”#006699″
Font-Bold=”True” ForeColor=”White” />
                    </asp:GridView>
        <asp:Button ID=”Button1″ runat=”server”
OnClick=”Button1_Click” Text=”导出” />

读取Excel数据的代码:那几个很粗大略的
private DataSet CreateDataSource()
    {
        string strCon;
        strCon = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” +
Server.MapPath(“excel.xls”) + “; Extended Properties=Excel 8.0;”;
        OleDbConnection olecon = new OleDbConnection(strCon);
        OleDbDataAdapter myda = new OleDbDataAdapter(“SELECT * FROM
[Sheet1$]”, strCon);
        DataSet myds = new DataSet();
        myda.Fill(myds);
        return myds;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = CreateDataSource();
        GridView1.DataBind();
    }

 

正文来源CSDN博客,转发请标明出处:http://blog.csdn.net/hanghwp/archive/2007/04/30/1593430.aspx

相关文章