zoukankan      html  css  js  c++  java
  • GridView的常用用法总结说明

    在ESSP的动态权限管理中遇到一个问题。CheckBox列没办法进入编辑状态。自己太笨,花了很久时间才解决这个问题。

    因为是手写数据源所以,应该在RowEditing方法里写上一段代码。原来直接创建一个SqlDatasource1控件的时候不需要在RowEditing事件里写这段代码(估计是封装好了).以下是对我有帮助的资料.声明为转载自http://beyondgxq.blog.163.com/blog/static/2758626020095159822766/

    GridView七种类型字段

    Field字段类型

    说明

    BoundField(数据绑定字段)

    将Data Source数据源的字段数据以文本方式显示

    ButtonField(按钮字段)

    在数据绑定控件中显示命令按钮。根据控件的不同,它可让您显示具有自定义按钮控件(例如【添加】或【移除】按钮)的数据行或数据列,按下时会引发RowCommand事件

    CommandField(命令字段)

    显示含有命令的Button按钮,包括了Select、Edit、Update、Delete命令按钮(DetailsView的CommandField才支持Insert命令)

    CheckBoxField(CheckBox字段)

    显示为CheckBox类型,通常用于布尔值True/False的显示

    HyperLinkField(超链接字段)

    将Data Source数据源字段数据显示成HyperLink超级链接,并可指定另外的NavigateUrl超链接

    ImageField(图像字段)

    在数据绑定控件中显示图像字段

    TemplateField(模板字段)

    显示用户自定义的模板内容

     

    GridView四种样式

    通过ControlStyle可设置BoundField字段服务器子控件的样式。

    通过FooterStyle可设置BoundField字段之页尾的样式。

    通过HeaderStyle可设置BoundField字段之页首的样式。

    通过ItemStyle可设置BoundField字段中数据项的样式。

     

    格式化字符串

    格式代号

    说  明

    原始格式

    格式指令

    运行结果

    {0:C}

    显示货币符号格式

    2005.5

    {0:C2}

    NT$2,005.50

    {0:D}

    显示十进制数格式(限用于整数)

    128

    {0:D}

    128

    {0:E}

    显示科学符号格式

    2005.5

    {0:E2}

    2.01E+003

    {0:F}

    显示固定小数字数格式

    2005.5

    {0:F4}

    2005.5000

    {0:G}

    显示一般格式

    2005.5

    {0:G}

    2005.5

    {0:N}

    显示有逗号固定小数字数格式

    2005.5

    {0:N3}

    2,005.500

    {0:P}

    显示百分比格式

    0.25

    {0:P}

    25.00%

    {0:X}

    显示十六进制数格式(限用于整数)

    128

    {0:X}

    80

    {0:#}

    显示自定义的数字格式

    2005.5

    {0:00####.00}

    002005.00

     

    各种类型字段使用方法

    BoundField :

    HeaderText  列名(在网页中显示出来的)

    HeaderImageUrl  列头的图片  

    DataField  数据源字段名

    NullDisplayText  当该字段的值为空时显示的值

    ButtonField:

    ButtonType  有Button?Image?Link三种

    DataTextField  将数据源字段数据绑定到Button按钮的文本属性中

    ImageUrl  当按钮形式为Image时,指定Image所在的Url

    CommandName  单击ButtonField按钮时所要运行的命令名称

    相关事件:

    当ButtonField按钮字段被按下时,GridView控件会引发RowCommand事件,

    若要判断引发命令事件之数据行的索引,请使用事件自变量的CommandArgument属性,会将该事件自变量传递至数据绑定控件的命令事件,ButtonField类会自动用适当的索引值填入CommandArgument属性。在事件响应函数中可以根据不同的CommandName来做不同的操作。

    从事件中判断e.CommandName和对第几行进行的操作e.CommandArgument。

    Example:

    if (e.CommandName == "Select")

            {

                int index = Convert.ToInt32(e.CommandArgument);

            }

    }

     

    CommandField:

    五种命令:Select、Edit、Update、Delete与Insert。显示及隐藏命令按钮您可以设置ShowDeleteButton、ShowEditButton、ShowInsertButton与 ShowSelectButton这几个属性(True或False)。而设置不同命令按钮的文字标题可用的属性有SelectText、 InsertText、UpdateText、DeleteText、CancelText、EditText、NewText。

    若您将ButtonType属性设为ButtonType.Image,则可以设置按钮的图像Url属性,可供使用的有CancelImageUrl、 DeleteImageUrl、EditImageUrl、InsertText、NewImageUrl、SelectImageUrl、 UpdateImageUrl。

    SelectedRowStyle 用于设置选中行的风格

    相关事件:

    RowEditing  

    RowDeleting

    RowUpdating

    RowCancelingEdit

    注意:RowEditing和RowUpdating的不同

    Example:( 摘自:http://hi.baidu.com/70zz)

    后台代码:

    你可以使用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();

         }

     

    //更新

    //gridview的列、行都是从0开始编号的

    //我在用“GridView1.DataKeys[e.RowIndex].Value.ToString()”老是报“索引超出范围“,不知原因。

    //建议改用后文写的”如何获取 GridView 编辑状态下单元格里的值“的方法

         protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

         {

             sqlcon = new SqlConnection(strCon);

             string sqlstr = "update 表 set 字段1='"

                 + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段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();

    //若在页面配置了数据源SqlDataSource1,用下2行代码,不过在页面里不要加SqlDataSourceID=SqlDataSource1属性了

            //GridView1.DataSource = SqlDataSource1;

            //GridView1.DataBind();

         }

    }

     

    前台主要代码:

    <!--

        使用时曾碰到这样的问题:要激发OnRowUpdating="GridView1_RowUpdating"事件,必须先写了 OnRowEditing="GridView1_RowEditing"事件,不然会报”激发了未处理的事件RowEditing‘“,现在还没搞清楚什么原因。。。

    -->                             ... ...

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

     

    CheckBoxField:

    DataField     设置绑定至数据源的字段名称

    Text     设置CheckBox右侧的说明文字

    ReadOnly     在编辑模式时,设置ReadOnly属性可以防止被编辑

     

    HyperLinkField

    DataTextField    绑定数据源字段显示成超链接文字

    DataNavigateUrlFields     将数据字段绑定到超链接字段Url属性

    Target   如果设置为"_blank"表示在空白页中打开

     

    ImageField

    DataImageUrlField    设置绑定至ImageField对象ImageUrl属性的数据源字段名称

     

    TemplateField

    ItemTemplate    字段项目模板

    AlternatingItemTemplate 字段交替项目模板,若设置这个字段后,奇数行会显示ItemTemplate,偶数行显示AlternatingItemTemplate

    EditItemTemplate     编辑项目模板

     

    其他常见用法

    1 程序中动态设置表头名称

    gv.Columns[0].HeaderText=”表头”;

    2 修改时获取文本控件上的文本

    string card=((TextBox)CellGrid.Rows[e.RowIndex].Cells[1].Controls[0]).Text;

    获得其他类型的控件同理,将上面代码的控件类型做修改即可

    3 在每一行绑定数据时,会发生RowDataBound事件,可在这里添加相应的事件响应函数

    4 删除之前提示是否确定删除:

    在RowDataBound事件中加入该代码

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

    ((CheckBox)e.Row.FindControl("CheckBox1")).Attributes.Add("onclick","return confirm('XXX')");

    }

    5 AutoGenerateColumns  是否自动添加列,如果是的话意味着是通过程序代码来实现添加的

     

     

    分页的实现

    关键属性:

    AllowPaging设置为"True"

    PageSize设置每一行显示的行数

    Mode 分页样式,包含这四种:NextPreviousFirstLast、NumericFirstLast、NextPrevious、 Numeric(Numeric指显示数字;First、Last指最开始和最后一个;Next、Previous指上一个和下一个)

    FirstPageImageUrl、LastPageImageUrl、NextPageImageUrl、PreviousPageImageUrl分别指对应的图片

    PagerStyle 中HorizontalAlign、VerticalAlign、BorderStyle用于设置分页控制的样式

     

    关键事件

    OnPageIndexChanging分页事件

    当发生该事件后,重新绑定数据源

    Example:

    ArticleList.PageIndex = e.NewPageIndex;

    if (Session["SQLStr"] != null)

    {

       string SQLStr = Session["SQLStr"].ToString();

       GirdViewRefresh(SQLStr);

    }

     

    典型使用步骤:

    添加GridView控件,设置相关属性:

    Columns中添加相应的数据行

    RowStyle、AlternatingRowStyle设置数据行样式

    分页设置AllowPaging="True";PageSize设置每页好显示的行数

    SelectedRowStyle 设置选择行的样式

    在CS文件添加相应的响应函数:

    (1)Page_Load中绑定数据源:

    ArticleList.DataSource = ds.Tables[0].DefaultView;

    ArticleList.DataBind();

     

    (2)OnPageIndexChanging中更新页索引,重新绑定数据源

    ArticleList.PageIndex = e.NewPageIndex;

    if (Session["SQLStr"] != null)

    {

         string SQLStr = Session["SQLStr"].ToString();

         GirdViewRefresh(SQLStr);

    }

     

    (3)RowCommand加入事件响应

    if (e.CommandName == "Select")

            {

                int index = Convert.ToInt32(e.CommandArgument);

            }

    }

    ----------------------

    如何获取 GridView 编辑状态下单元格里的值

    ----------------------

    还在使用这样的代码吗?

    var txtName = grid1.Rows[e.RowIndex].Cells[0].FindControl("txtName") as TextBox;

    if (txtName != null)

    {

        // 读取值

        // GridView常用总结 - 冰雪聪明 - 冰天雪地若水

    }

    其实这些工作(在单元格中查找控件,并尝试获取其中的值)已经被封装了。现在,只要调用 ExtractValuesFromCell 方法即可。

    而该方法也被很多种列类型所支持:

    DataControlField, BoundField, AutoGeneratedField, CheckBoxField, ImageField, TemplateField, DynamicField

    你可以在 GridView 的 RowUpdating, RowDeleting 等事件中使用它。利用该方法,可以将值提取到所需的字典里去,然后再从字典中读取。这些字典包括:e.Keys, e.NewValues, e.OldValues 等。

    一小段例子代码:

        // 更新

        protected void grid1_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            var row = grid1.Rows[e.RowIndex];

            // 提取 Id 字段的值

            grid1.Columns[0].ExtractValuesFromCell(

                e.Keys,

                row.Cells[0] as DataControlFieldCell,

                DataControlRowState.Edit,

                true /* include readonly */);

            // 提取 Name 字段的值

            grid1.Columns[1].ExtractValuesFromCell(

                e.NewValues,

                row.Cells[1] as DataControlFieldCell,

                DataControlRowState.Edit,

                true /* include readonly */);

            var id = int.Parse(e.Keys["id"].ToString());

            var name = (string) e.NewValues["name"];

            // 执行相关的数据库更新操作

            // GridView常用总结 - 冰雪聪明 - 冰天雪地若水

        }

    这样,在大多数场合我们可以尽可能多的使用 BoundField,并且也能正确读取到其编辑时的值,省下自定义 TemplateField 的一堆代码了。

  • 相关阅读:
    【leetcode】1295. Find Numbers with Even Number of Digits
    【leetcode】427. Construct Quad Tree
    【leetcode】1240. Tiling a Rectangle with the Fewest Squares
    【leetcode】1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
    【leetcode】1291. Sequential Digits
    【leetcode】1290. Convert Binary Number in a Linked List to Integer
    【leetcode】1269. Number of Ways to Stay in the Same Place After Some Steps
    【leetcode】1289. Minimum Falling Path Sum II
    【leetcode】1288. Remove Covered Intervals
    【leetcode】1287. Element Appearing More Than 25% In Sorted Array
  • 原文地址:https://www.cnblogs.com/xryyforver/p/1519277.html
Copyright © 2011-2022 走看看