gridview_gridview分页 - CSDN
精华内容
参与话题
  • GridView使用详解

    万次阅读 多人点赞 2018-01-25 16:33:51
    GridView基本使用方法  GridView是一个在二维可滚动的网格中展示内容的控件。网格中的内容通过使用adapter自动插入到布局中。  下面通过实现一个简单的显示省份名的demo,介绍GridView控件的基本使用方法: 在...

    GridView基本使用方法

      GridView是一个在二维可滚动的网格中展示内容的控件。网格中的内容通过使用adapter自动插入到布局中。
      下面通过实现一个简单的显示省份名的demo,介绍GridView控件的基本使用方法:

    在布局中使用GridView控件,实现activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.sunxiaodong.androidgridview.MainActivity">
    
        <GridView
            android:id="@+id/grid_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:columnWidth="90dp"
            android:gravity="center"
            android:horizontalSpacing="10dp"
            android:numColumns="auto_fit"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />
    
    </RelativeLayout>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

      这个GridView会填充满整个屏幕,关于使用属性的说明,在下一节“GridView主要属性详解”中将进行说明。

    MainActivity.java中,获取GridView控件,并进行初始化设置

    public class MainActivity extends AppCompatActivity {
    
        private GridView mGridView;
        private ProvinceAdapter mProvinceAdapter;
        private String[] provinceNames = new String[]{"北京", "上海", "广东", "广西", "天津", "重庆", "湖北", "湖南", "河北", "河南", "山东"};
        private int[] bgColor = new int[]{R.color.color_00ff00, R.color.color_ff0000, R.color.color_ff0000, R.color.color_ffff00,
                R.color.color_8e35ef, R.color.color_303F9F, R.color.color_00ff00, R.color.color_ff0000, R.color.color_ff0000,
                R.color.color_ffff00, R.color.color_8e35ef};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initView();
        }
    
        private void initView() {
            mGridView = (GridView) this.findViewById(R.id.grid_view);
            List<ProvinceBean> provinceBeanList = new ArrayList<>();
            for (int i = 0; i < provinceNames.length; i++) {
                ProvinceBean provinceBean = new ProvinceBean();
                provinceBean.setName(provinceNames[i]);
                provinceBean.setColor(bgColor[i]);
                provinceBeanList.add(provinceBean);
            }
            mProvinceAdapter = new ProvinceAdapter(this, provinceBeanList);
            mGridView.setAdapter(mProvinceAdapter);
        }
    
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

      程序中,首先使用findViewById方法获取到了GridView控件,接下来使用setAdapter方法给它设置提供数据的适配器。程序中,引入了两份数据provinceNames 和bgColor,其中provinceNames定义了依次显示在GridView各网格中的省份名称,bgColor定义了依次显示在GridView网格中的省份名称的背景色,这些只是为了更方便读者从视觉上认识GridView。

    创建ProvinceAdapter.java文件,实现数据在GridView中的展示

    public class ProvinceAdapter extends BaseAdapter {
    
        private List<ProvinceBean> provinceBeanList;
        private LayoutInflater layoutInflater;
    
        public ProvinceAdapter(Context context, List<ProvinceBean> provinceBeanList) {
            this.provinceBeanList = provinceBeanList;
            layoutInflater = LayoutInflater.from(context);
        }
    
        @Override
        public int getCount() {
            return provinceBeanList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return provinceBeanList.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.province_grid_view_item_layout, null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            ProvinceBean provinceBean = provinceBeanList.get(position);
            if (provinceBean != null) {
                holder.text.setText(provinceBean.getName());
                holder.text.setBackgroundResource(provinceBean.getColor());
            }
            return convertView;
        }
    
        class ViewHolder {
            TextView text;
        }
    
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

      ProvinceAdapter继承自BaseAdapter,有几个必须实现的方法getCount()getItem(int position)getItemId(int position)getView(int position, View convertView, ViewGroup parent)。其中,getCount()返回需要展示的GridView的项数。getItem(int position)返回给定位置的数据对象。getItemId(int position)返回该项的行id。getView(int position, View convertView, ViewGroup parent)是必须要实现的方法,该方法控制GridView中数据项的显示,方法中的convertView视图是被复用的视图,在实现时对其进行判断,如果为null,则新建视图,否则直接复用视图。

      上面程序的执行效果如下图所示:
    这里写图片描述

    GridView的属性和方法详解

    GridView的主要属性

    • android:columnWidth
      相关方法setColumnWidth(int)。定义每一列的固定宽度。
      必须是dimension值(浮点数后面拼接单位,例如“14.5sp”)。有效的单位有:px,dp,sp,in,mm。
      它也可以是一个资源的引用(@[package:]type:name)或主题属性(?[package:][type:]name)。
    • android:gravity
      相关方法setGravity(int)。定义每一个单元格的重心。
      必须是一个或多个(使用“|”分隔)下面的常量
    常量 描述
    top 0x30 将对象放在它的容器的顶部,不会改变它的大小
    bottom 0x50 将对象放在它的容器的底部,不会改变它的大小
    left 0x03 将对象放在它的容器的左面,不会改变它的大小
    right 0x05 将对象放在它的容器的右面,不会改变它的大小
    center_vertical 0x10 将对象放在它的容器垂直方向的中心,不会改变它的大小
    fill_vertical 0x70 如果需要改变对象的垂直大小以完全填充它的容器
    center_horizontal 0x01 将对象放在它的容器水平方向的中心,不会改变它的大小
    fill_horizontal 0x07 如果需要改变对象的水平大小以完全填充它的容器
    center 0x11 将对象放在它的容器的中心,不会改变它的大小
    fill 0x77 如果需要改变对象的水平和垂直方向的大小以完全填充它的容器
    clip_vertical 0x80 附加选项被设置用来将子视图的上面或下面边缘裁剪到它的容器的边界。这个裁剪基于垂直方向的重心:top重心将会裁剪底部边缘,bottom重心将会裁剪顶部边缘,不会同时裁剪两边
    clip_horizontal 0x08 附加选项被设置用来将子视图的左面或右面边缘裁剪到它的容器的边界。这个裁剪基于水平方向的重心:left重心将会裁剪右面边缘,right重心将会裁剪左面边缘,不会同时裁剪两边
    start 0x00800003 将对象放在它的容器的起始位置,不会改变它的大小
    end 0x00800005 将对象放在它的容器的末尾位置,不会改变它的大小
    • android:horizontalSpacing
      相关方法setHorizontalSpacing(int)。定义了两列之间的水平间隔。
      属性设置要求同android:columnWidth
    • android:numColumns
      相关方法setNumColumns(int)。定义了展示的列数。
      可以是一个整形值,如“100”。也可以是一个资源的引用(@[package:]type:name)或主题属性(?[package:][type:]name)。或者下面的这个常量:
    常量 描述
    auto_fit -1 在有效空间展示尽量多的列数
    • android:stretchMode
      相关方法setStretchMode(int)。定义了列拓展填充有限闲置空间的方式。
      必须是下面常量值中的一个:
    常量 描述
    none 0 扩展无效
    spacingWidth 1 列与列之间的空间被扩展
    columnWidth 2 每一列被相等的拓展
    spacingWidthUniform 3 列与列之间的空间被均匀的扩展
    • android:verticalSpacing
      相关方法setVerticalSpacing(int)。定义两行之间的垂直间隔。
      属性设置要求同android:columnWidth

    GridView的主要方法

    Public方法
    • ListAdapter:getAdapter()
      返回关联的Adapter
    • int:getColumnWidth()
      返回列的宽度
    • int:getGravity()
      返回描述子视图被放置的方式的标识。默认为Gravity.LEFT
    • int:getHorizontalSpacing()
      返回列间的水平间隔大小。
      仅会计算当前布局。如果调用了setHorizontalSpacing(int)来设置间隔,但布局还没有完成,这个方法会返回一个旧值。如果想要明确地获取这个间隔,使用getRequestedHorizontalSpacing()方法请求。
    • int:getNumColumns()
      返回列数。如果网格没有被布局,则返回AUTO_FIT
    • int:getRequestedColumnWidth()
      返回请求的列宽度。
      这可能不是真实的列宽度。使用getColumnWidth()获取当前真实的列宽度。
    • int:getRequestedHorizontalSpacing()
      返回请求的列间的水平间隔。
      这个值可能是布局期间的局部样式,也可能是默认的样式,或是使用setHorizontalSpacing(int)方法设置的值。如果布局尚未完成或GridView计算得到了一个和请求的不同的水平间隔,它与getHorizontalSpacing()将有不同的返回值。
    • int:getStretchMode()
      返回扩展模式。
    • int:getVerticalSpacing()
      返回行间的垂直间隔。
    • onInitializeAccessibilityNodeInfoForItem(View view, int position, AccessibilityNodeInfo info)
      使用列表中实际项的信息初始化一个AccessibilityNodeInfo
    参数 描述
    View 呈现列表项的视图
    position 在Adapter中列表项的位置
    info 需要初始化的信息项(Node Info)
    • boolean:onKeyDown(int keyCode, KeyEvent event)
      KeyEvent.Callback.onKeyDown()的默认实现:如果视图可点击,当KEYCODE_DPAD_CENTERKEYCODE_ENTER被释放时,执行视图按下事件。
      软键盘上的按键事件通常不会触发这个监听,尽管有些条件下可能会触发,但不要依赖它去捕获关键盘按键事件。
      返回值:处理返回true,否则返回false。
    • boolean:onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
      KeyEvent.Callback.onKeyMultiple()的默认实现:一直返回false。
      软键盘上的按键事件通常不会触发这个监听,尽管有些条件下可能会触发,但不要依赖它去捕获关键盘按键事件。
      返回值:处理返回true,否则返回false。
    • boolean:onKeyUp(int keyCode, KeyEvent event)
      KeyEvent.Callback.onKeyUp()的默认实现:当KEYCODE_DPAD_CENTERKEYCODE_ENTER被释放时,执行视图点击事件。
      软键盘上的按键事件通常不会触发这个监听,尽管有些条件下可能会触发,但不要依赖它去捕获关键盘按键事件。
      返回值:处理返回true,否则返回false。
    • setAdapter(ListAdapter adapter)
      为GridView设置数据。
    • setColumnWidth(int columnWidth)
      设置宽度。
    • setGravity(int gravity)
      设置网格的中重心。重心描述了子视图的摆放方式。默认是Gravity.LEFT
    • setHorizontalSpacing(int horizontalSpacing)
      设置列间的水平间隔。
    • setNumColumns(int numColumns)
      设置列数。
    • setRemoteViewsAdapter(Intent intent)
      设置该AbsListView使用远程视图适配器,该适配器通过特定的Intent连接到一个RemoteViewsService。
    • setSelection(int position)
      设置当前选中项。
    • setStretchMode(int stretchMode)
      设置列表项如何拓展填充闲置空间的方式。
      可以设置下面常量值中的一个:
    常量 描述
    NO_STRETCH 0 扩展无效
    STRETCH_COLUMN_WIDTH 2 扩展列
    STRETCH_SPACING 1 扩展列间的空间
    STRETCH_SPACING_UNIFORM 3 均匀地扩展列间的空间
    • setVerticalSpacing(int verticalSpacing)
      设置行间的垂直间隔。
    • smoothScrollByOffset(int offset)
      平滑地滚动到具体的适配器位置的偏移位置。视图会滚动到指定位置显示出来。
    • smoothScrollToPosition(int position)
      平滑地滚动到具体的适配器位置。视图会滚动到指定位置显示出来。
    Protected方法
    • attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count)
      子视图可以覆写该方法来在提供的child上设置布局动画参数。
    参数 描述
    child 和动画参数关联的子视图
    params 持有动画参数的子视图的布局参数
    index 子视图在视图组中的索引
    count 视图组中子视图的数量
    • computeVerticalScrollExtent()
      计算滚动条把手在纵向滚动范围内占用的幅度。该值用于计算滚动条把手在滚动条滑道中的长度。
      范围使用与computeVerticalScrollRange()computeVerticalScrollOffset()相同的任意单位。
      默认的长度是视图的可绘制高度。
      返回值:滚动条把手在纵向滚动范围内占用的幅度。
    • computeVerticalScrollOffset()
      计算滚动条把手在纵向滚动范围内的位置。该值用于计算滚动条把手在滚动条滑道中的位置。
      范围使用与computeVerticalScrollRange()computeVerticalScrollExtent()相同的任意单位。
      默认位置是视图的滚动条位置。
      返回值:滚动条把手的纵向位置
    • computeVerticalScrollRange()
      计算垂直滚动条的垂直范围。
      范围使用与computeVerticalScrollExtent()computeVerticalScrollOffset()相同的任意单位。
      返回值:纵向滚动条代表的整个纵向范围。默认纵向范围时视图的绘制高度。
    • layoutChildren()
      子类必须实现该方法,来布局子视图
    • onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)
      当视图焦点状态改变时,视图系统调用该方法。由定向导航导致的焦点变更时,direction和previouslyFocusedRect提供了焦点是从那里来的进一步信息。
    参数 描述
    gainFocus 如果视图具有焦点,值为真;否则为假
    direction 当调用requestFocus()为该视图设置焦点时,该值为焦点移动的方向。其值为FOCUS_UP、FOCUS_DOWN、FOCUS_LEFT或者FOCUS_RIGHT
    previouslyFocusedRect 失去焦点的视图的矩形坐标,使用该视图的坐标系统.如果指定了,它将传入可以知道焦点来自哪里的详细信息(作为对direction 的补充)。否则,其值为null
    • onMeasure(int widthMeasureSpec, int heightMeasureSpec)
      对视图及其内容进行测量,来决定布局的宽和高。
    展开全文
  • C#精髓 第四讲 GridView 72般绝技

    万次阅读 多人点赞 2012-05-14 09:41:02
    说明:准备出一个系列,...C#精髓第四讲 GridView 72般绝技作者:清清月儿 主页:http://blog.csdn.net/21aspnet/ 时间:2007.3.24-26为了写本文,又搭工又搭料,累的2天2宿没睡觉,这篇文章实在是耗费我太多的心血

    说明:准备出一个系列,所谓精髓讲C#语言要点。这个系列没有先后顺序,不过尽量做到精。可能会不断增删整理,本系列最原始出处是csdn博客,谢谢关注。

    C#精髓

    第四讲 GridView 72般绝技

    作者:清清月儿

    主页:http://blog.csdn.net/21aspnet/           时间:2007.3.24-26

    为了写本文,又搭工又搭料,累的2天2宿没睡觉,这篇文章实在是耗费我太多的心血,版权永远属于CSDN社区的,请不要试图修改本文,破坏全文的完整性,希望您尊重我的劳动成果!

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

    =================================

    如果你喜欢《GridView 72般绝技》这个博客帖子,那么你应该喜欢我的新书

    我的新书《asp.net开发技巧精讲》

    2011.12.12日,写在我的新书开印之前 

    =================================



     

    1.GridView无代码分页排序

    效果图:

    1.AllowSorting设为True,aspx代码中是AllowSorting="True";
    2.默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。
    3.默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。

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

    效果图:

    后台代码:
    你可以使用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;

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

    //更新
        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() + "',字段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();
        }

    //绑定
        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();
        }
    }

    前台主要代码:
                                ... ...
    <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>


    3.GridView正反双向排序:
    效果图:点姓名各2次的排序,点其他也一样可以。

    后台代码:
    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();
        }

        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="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 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>

     

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

    效果图:

    后台代码:
    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();
        }

    前台主要代码:
    <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:TemplateField HeaderText="员工性别">
                                    <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>

    5.GridView和CheckBox结合:

    效果图:

    后台代码:

    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 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)
                {

                    string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.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();
        }
    }

    前台主要代码:

    <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" />

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

    效果图:

    做法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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");
                }
            }

        }

    前台代码:
    <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" 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="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"
                SelectCommand="SELECT top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>
       
        </div>
        </form>
    </body>
    </html>

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

    效果图:

    做法:和上面的一样就是代码不同
    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'");
            }

        }

    8.GridView实现删除时弹出确认对话框:

    效果图:

    实现方法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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 + "/"吗?')");
                }
            }

        }

    9.GridView实现自动编号:

    效果图:

    实现方法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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 + "/"吗?')");
                //}

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

        }

     

    注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
    <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>

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

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

    图2-格式化后

    解决方法:

    在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的

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

    主要是由于htmlencode属性默认设置为true,已防止XSS攻击,安全起见而用的,所以,可以有以下两种方法解决

    1、

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

    将htmlencode设置为false即可

    另外的解决方法为,使用模版列

    <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>

    前台代码:
    <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:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" />
                    <asp:BoundField DataField="姓名" HeaderText="姓名" 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="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"
                SelectCommand="SELECT top 5 [出生日期], [起薪], [身份证号码], [姓名], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>

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

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

    效果图:

    解决方法:数据绑定后过滤每一行即可
    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);
                }
            } 

    调用的方法:

        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;

    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() + "',家庭住址='"
                + ((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'");

                当有编辑列时,避免出错,要加的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();
            }

        }
    }

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

    效果图:

    首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  ItemStyle-Width="100" />
    gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
    原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。

    如果要给所有的列增加此属性:
     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显示隐藏某一列:
    本方案为月儿独创,不同于网上其他方式,我觉得用一个CheckBox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!

    效果图:
    图1-开始

    图2-点击显示的CheckBox后

    解决方案:
    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;//如果不这样后面的代码会把他True

        }

    双击CheckBox1,在CheckedChanged方法里写上代码,最后代码如下:
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
             GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;
             Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.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 身份证号码='" + 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() + "',家庭住址='"
                + ((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的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());
        }
    }

    前台代码:
    <!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弹出新页面/弹出制定大小位置新窗口:

    效果图:

    方案一:简单的方法,新窗口不固定大小
     <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: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是路径。

    方案二:精确控制弹出窗口大小位置
    <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   即可!

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

    效果图:

    代码:
    <!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;
       }

    .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" >

    15.GridView合并表头多重表头无错完美版(以合并3列3行举例)

    效果图:


    后台代码:
    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>";

                    //第二行表头
                    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>";

                    //第三行表头
                    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">

    <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>

    16.GridView突出显示某一单元格(例如金额低于多少,分数不及格等)

    效果图:

    解决方案:主要是绑定后过滤
     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();

    全部后台代码:

    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">

    <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 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>

     17.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();
               
            }
        }
    }
    前台:唯一的花头就是设置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>

     

     18.GridView数据导入Excel/Excel数据读入GridView

    效果图:

    解决方案:
    页面增加一个按钮,单击事件添加如下方法:
    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();
        }

    由于时间关系,这个文章先到此。有时间再写,其实还有很多技巧,不过我觉得如果能融汇贯通应该可以举一反三

    =================================

    如果你喜欢《GridView 72般绝技》这个博客帖子,那么你应该喜欢我的新书

    我的新书《asp.net开发技巧精讲》

    2011.12.12日,写在我的新书开印之前 

    =================================

     

    展开全文
  • GridView 使用介绍

    2019-07-04 14:10:52
    GridView属性 基本使用 出现的问题及异常 GridView属性 android:numColumns=”auto_fit” //GridView的列数设置为自动 android:columnWidth=”90dp " //每列的宽度,也就是Item的宽度 android:stretchMode=”...

    目录

    GridView属性

    基本使用

    出现的问题及异常


    GridView属性

    android:numColumns=”auto_fit”   //GridView的列数设置为自动
    android:columnWidth=”90dp "        //每列的宽度,也就是Item的宽度
    android:stretchMode=”columnWidth"  //缩放与列宽大小同步
    android:verticalSpacing=”10dp”          //两行之间的边距
    android:horizontalSpacing=”10dp”      //两列之间的边距 
    android:cacheColorHint="#00000000" //去除拖动时默认的黑色背景
    android:listSelector="#00000000"        //去除选中时的黄色底色
    android:scrollbars="none"                   //隐藏GridView的滚动条
    android:fadeScrollbars="true"             //设置为true就可以实现滚动条的自动隐藏和显示
    android:fastScrollEnabled="true"      //GridView出现快速滚动的按钮(至少滚动4页才会显示)
    android:fadingEdge="none"                //GridView衰落(褪去)边缘颜色为空,缺省值是vertical。(可以理解为上下边缘的提示色)
    android:fadingEdgeLength="10dip"   //定义的衰落(褪去)边缘的长度
    android:stackFromBottom="true"       //设置为true时,你做好的列表就会显示你列表的最下面
    android:transcriptMode="alwaysScroll" //当你动态添加数据时,列表将自动往下滚动最新的条目可以自动滚动到可视范围内
    android:drawSelectorOnTop="false"  //点击某条记录不放,颜色会在记录的后面成为背景色,内容的文字可见(缺省为false)

    基本使用

    1,GridView 所在的Activity 的layout

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.activity.GameDetailActivity">
    
        
        <GridView
            android:id="@+id/gv_detail_prize_list"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:horizontalSpacing="45dp"
            android:layout_marginLeft="80dp"
            android:layout_marginRight="80dp"
            android:layout_gravity="center"
            android:numColumns="8"
            android:layout_marginBottom="34dp"
            android:layout_alignParentBottom="true"/>
    
    
    </RelativeLayout>

    注意:如果不设置android:numColumns="8"属性,则默认只有一列,且纵向显示所有的数据;

    2,GridView item的布局

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="265dp"
        android:orientation="vertical"
        android:background="@drawable/shape_prize_bg">
    
        <ImageView
            android:id="@+id/iv_prize_item"
            android:layout_gravity="center"
            android:layout_width="180dp"
            android:layout_height="180dp"
            android:background="@drawable/shape_prize_image_bg"/>
    
        <TextView
            android:id="@+id/tv_prize_name_item"
            android:layout_width="wrap_content"
            android:layout_height="85dp"
            android:paddingLeft="10dp"
            android:paddingTop="10dp"
            android:textColor="#ffffff"
            android:background="@drawable/shape_prize_name_bg"
            android:textSize="24dp"/>
    
    </LinearLayout>

    注意:如果ImageView的
            android:layout_width="180dp"
            android:layout_height="180dp"属性设置成wrap_content,GridView不显示,原因不太清楚。

    3,定义数据Adapter

    public class PrizeAdapter extends BaseAdapter {
        private List<DetailPrize> imgUrls = new ArrayList<>();
    
        private Context context;
    
        public void setData(List<DetailPrize> imgUrls, Context context) {
            this.imgUrls.clear();
            this.context = context;
            if (imgUrls != null) {
                this.imgUrls.addAll(imgUrls);
            }
            notifyDataSetChanged();
        }
    
    
        @Override
        public int getCount() {
            return imgUrls.size();
        }
    
        @Override
        public Object getItem(int position) {
            return null;
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                vh = new ViewHolder();
                convertView = View.inflate(context, R.layout.game_grid_item, null);
                vh.iv = convertView.findViewById(R.id.iv_prize_item);
                vh.tv_prize_name_item = convertView.findViewById(R.id.tv_prize_name_item);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
    //            Glide.with(convertView).load(imgUrls.get(position)).into(vh.iv);
            }
            com.orhanobut.logger.Logger.d("奖品图片URL" + imgUrls.get(position));
            Glide.with(context ).load(imgUrls.get(position).getImgUrl()).into(vh.iv);
            vh.tv_prize_name_item.setText(imgUrls.get(position).getPrizeName());
    //        ImageLoader.getInstance().displayImage(list.get(i).getUrl(),vh.iv,Config.display());
            return convertView;
        }
    
        class ViewHolder {
            ImageView iv;
            TextView tv_prize_name_item;
        }
    }
    
    
    
    //给Adapter传递数据的java bean
    public class DetailPrize {
    
        private String imgUrl;
        private String prizeName;
    
        public DetailPrize(String imgUrl, String prizeName) {
            this.imgUrl = imgUrl;
            this.prizeName = prizeName;
        }
    
        public String getImgUrl() {
            return imgUrl;
        }
    
        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }
    
        public String getPrizeName() {
            return prizeName;
        }
    
        public void setPrizeName(String prizeName) {
            this.prizeName = prizeName;
        }
    }
    
    

    4,绑定视图和数据

    在GridView所在的Activity中绑定数据

    private GridView gv_detail_prize_list;
    private PrizeAdapter adapter;
    gv_detail_prize_list = findViewById(R.id.gv_detail_prize_list);
    adapter = new PrizeAdapter();
    gv_detail_prize_list.setAdapter(adapter);
    
    //监听Item点击事件
    gv_detail_prize_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              Toast.makeText(GridViewActivity.this, " position " + position , Toast.LENGTH_LONG).show();
          }
    });

    5,加载网络获取的数据

    //获取到网络数据之后更新GridView
    public void updateGamePrize() {
            List<DetailPrize> prizes = new ArrayList<>();
            for (int i = 0; i < 8; i++) {
                prizes.add(new DetailPrize("http://pic15.nipic.com/20110628/1369025_192645024000_2.jpg", "商品名"+i));
            }
            //显示网络加载的数据
            adapter.setData(prizes, this);
    }

    出现的问题及异常

    1,item不显示或者GridView不显示的问题

    可能的原因:item的布局中的控件没有指定大小,比如item的布局有个ImageView控件,宽高指定为wrap_centent,没有指定固定大小,比如30db;或者给GridView设置android:columnWidth=”30dp” 属性;

    2,出现如下图的问题(item的根据也设置固定值大小,但是感觉每个显示item的宽度比实际设置的值要大):

    可能原因:GridView大小固定,但是设置的android:horizontalSpacing="36dp"属性值和每个item设置的固定值小于GridView显示的区域值;导致item显示宽度比实际设置的值大,来铺满GridView区域;设置android:stretchMode=”columnWidth"属性  //缩放与列宽大小同步

    展开全文
  • GridView功能详细介绍

    千次阅读 热门讨论 2008-03-28 10:34:00
    快速预览:GridView无代码分页排序GridView选中,编辑,取消,删除GridView正反双向排序GridView和下拉菜单DropDownList结合GridView和CheckBox结合鼠标移到GridView某一行时改变该行的背景色方法一鼠标移到GridView...

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

    1.GridView无代码分页排序

    效果图:

    1.AllowSorting设为True,aspx代码中是AllowSorting="True";
    2.默认1页10条,如果要修改每页条数,修改PageSize即可,在aspx代码中是PageSize="12"。
    3.默认的是单向排序的,右击GridView弹出“属性”,选择AllowSorting为True即可。


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

    效果图:

    后台代码:
    你可以使用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;

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

    //更新
        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() + "',字段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();
        }

    //绑定
        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();
        }
    }

    前台主要代码:
                                ... ...
    <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>


    3.GridView正反双向排序:
    效果图:点姓名各2次的排序,点其他也一样可以。

    后台代码:
    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();
        }

        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="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 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>

     

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

    效果图:

    后台代码:
    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();
        }

    前台主要代码:
    <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:TemplateField HeaderText="员工性别">
                                    <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>

    5.GridView和CheckBox结合:

    效果图:

    后台代码:

    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 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)
                {

                    string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + GridView1.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();
        }
    }

    前台主要代码:

    <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" />

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

    效果图:

    做法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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");
                }
            }

        }

    前台代码:
    <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" 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="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"
                SelectCommand="SELECT top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>
       
        </div>
        </form>
    </body>
    </html>

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

    效果图:

    做法:和上面的一样就是代码不同
    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'");
            }

        }

    8.GridView实现删除时弹出确认对话框:

    效果图:

    实现方法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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 + "/"吗?')");
                }
            }

        }

    9.GridView实现自动编号:

    效果图:

    实现方法:
    双击GridView的OnRowDataBound事件;
    在后台的GridView1_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 + "/"吗?')");
                //}

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

        }

     

    注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
    <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>

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

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

    图2-格式化后

    解决方法:

    在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的

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

    主要是由于htmlencode属性默认设置为true,已防止XSS攻击,安全起见而用的,所以,可以有以下两种方法解决

    1、

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

    将htmlencode设置为false即可

    另外的解决方法为,使用模版列

    <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>

    前台代码:
    <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:BoundField DataField="身份证号码" HeaderText="身份证号码" ReadOnly="True" SortExpression="身份证号码" />
                    <asp:BoundField DataField="姓名" HeaderText="姓名" 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="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:北风贸易ConnectionString1 %>"
                SelectCommand="SELECT top 5 [出生日期], [起薪], [身份证号码], [姓名], [家庭住址], [邮政编码] FROM [飞狐工作室]" DataSourceMode="DataReader"></asp:SqlDataSource>

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

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

    效果图:

    解决方法:数据绑定后过滤每一行即可
    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);
                }
            } 

    调用的方法:

        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;

    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() + "',家庭住址='"
                + ((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'");

                当有编辑列时,避免出错,要加的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();
            }

        }
    }

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

    效果图:

    首先设置<asp:BoundField DataField="家庭住址" HeaderText="家庭住址"  ItemStyle-Width="100" />
    gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
    原因是连续英文段为一个整体导致的,在RowDataBound中添加上了一句e.Row.Cells[2].Style.Add("word-break", "break-all")就可以。

    如果要给所有的列增加此属性:
     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显示隐藏某一列:
    本方案为月儿独创,不同于网上其他方式,我觉得用一个CheckBox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!

    效果图:
    图1-开始

    图2-点击显示的CheckBox后

    解决方案:
    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;//如果不这样后面的代码会把他True

        }

    双击CheckBox1,在CheckedChanged方法里写上代码,最后代码如下:
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
             GridView1.Columns[3].Visible=! GridView1.Columns[3].Visible;
             Response.Write("GridView1的第4列现在的显示隐藏状态是:"+GridView1.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 身份证号码='" + 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() + "',家庭住址='"
                + ((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的第4列现在的显示隐藏状态是:"+GridView1.Columns[3].Visible.ToString());
        }
    }

    前台代码:
    <!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弹出新页面/弹出制定大小位置新窗口:

    效果图:

    方案一:简单的方法,新窗口不固定大小
     <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: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是路径。

    方案二:精确控制弹出窗口大小位置
    <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   即可!

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

    效果图:

    代码:
    <!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;
       }

    .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" >

    15.GridView合并表头多重表头无错完美版(以合并3列3行举例)

    效果图:


    后台代码:
    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>";

                    //第二行表头
                    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>";

                    //第三行表头
                    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">

    <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>

    16.GridView突出显示某一单元格(例如金额低于多少,分数不及格等)

    效果图:

    解决方案:主要是绑定后过滤
     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();

    全部后台代码:

    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">

    <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 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>

     17.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();
               
            }
        }
    }
    前台:唯一的花头就是设置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>

     

     18.GridView数据导入Excel/Excel数据读入GridView

    效果图:

    解决方案:
    页面增加一个按钮,单击事件添加如下方法:
    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();
        }

     
    展开全文
  • 今天我们来模仿一下支付宝钱包首页中带有分割线的GridView,俗称九宫格。 详情:http://blog.csdn.net/finddreams 其实实现这种效果并不难,原理就是让每个item都设置成带有分割线的背景,这样就很容易实现了。
  • GridView

    2019-03-18 08:50:39
    GridView组件用来以网格方式排列视图,当屏幕上有很多元素需要显示时,可以使用该组件。 GridView常用属性 android:numColumns="auto_fit" 总列数 android:columnWidth="90dp" 列宽 android:...
  • Android入门第八篇之GridView(九宫图)

    万次阅读 多人点赞 2009-09-18 16:55:00
    本文来自http://blog.csdn.net/hellogv/ GridView跟ListView都是比较常用的多控件...GridView的用法很多,网上介绍最多的方法就是自己实现一个ImageAdapter继承BaseAdapter,再供GridView使用,类似这种的方法本文不
  • Android:控件GridView的使用

    万次阅读 2019-12-05 10:43:27
    如果是列表(单列多行形式)的使用ListView,如果是多行多列网状形式的优先使用GridView。 <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android=...
  • GridView嵌套GridView

    2019-07-06 07:30:57
    下一个示例演示如何在单个网格中显示一个完整的分组产品列表,如下图所示:使用的基本技术是为附表创建一个GridView,它的每行又嵌入一个GridView,这些子GridView使用TemplateField来插入到父GridView中。...
  • 在Android开发中,我们常常用到ListView和GridView,而有的时候系统的ListView,GridView并不能满足我们的需求,所以我们需要自己定义一个ListView或者GridView,我的上一篇文章中就是自定义的一个左右滑动删除item的...
  • 这个功能主要是在数据结构这一块,先上图看看效果:重点 是放在左边这个listview嵌套gridview,可删除gridview中item,也可点击最后一项手动增加item数据,这里看几行重要的代码,源码放在底部,可供下载android...
  • GridView详解

    千次阅读 2016-03-27 00:16:49
    GridView详解
  • Asp.net 2.0中新增的gridview控件,是十分强大的数据展示控件,在前面的系列文章里,分别展示了其中很多的基本用法和技巧(详见中Gridview控件高级技巧>)。在本文中,将继续探讨有关的技巧。 一、Gridview中的内容...
  • GridView是ViewGroup子类,主要用于显示在一个二维可滚动的网格,比如九宫格。使用gridview和listview类似,都是使用ListAdapter来填充数据加载布局,如果以列间距拉伸,则不需要指定列之间的间距;如果以列的等宽度...
  • 文章是参考博客http://blog.csdn.net/eastmount/article/details/41808179完成,主要讲述通过GridView控件点击加号图片动态添加本地相册图片,点击图片可以删除已...同时界面比较美观。 免费资源,希望对大家有所帮助。
  • [Android] 通过GridView仿微信动态添加本地图片

    万次阅读 热门讨论 2020-06-28 23:15:47
    此篇文章主要讲述通过GridView控件实现添加本地图片并显示.主要是关于GridView控件的基本操作,通过调用SimpleAdapter适配器实现实现加载图片,在gridView1.setOnItemClickListener()点击函数中响应不同操作.当点击...
  • Android中GridView使用

    万次阅读 多人点赞 2012-09-06 16:06:07
    GridView(网格视图)是按照行列的方式来显示内容的,一般用于显示图片,图片等内容,比如实现九宫格图,用GridView是首选,也是最简单的。主要用于设置Adapter。 GridView常用的XML属性:   属性名称 ...
  • Flutter网格控件GridView

    千次阅读 2019-03-19 15:57:09
    Flutter GridView用法详解。Flutter GridView异步加载
  • GridView添加HeaderView

    万次阅读 热门讨论 2014-09-09 23:47:29
    实现这个功能一般有两种思路,一种思路是使用ScrollView+GridView,第二种思路是使用ListView来实现GridView的效果。 第一种思路的具体实现是把HeaderView和GridView都放到ScrollView里面,这里要解决的问题是...
  • Asp.Net 控件 GridView

    千次阅读 2013-11-14 15:58:29
    c#实现简单地界面的增删查改(用的mysql数据库),带你了解GridView控件
1 2 3 4 5 ... 20
收藏数 103,001
精华内容 41,200
关键字:

gridview