GridView实用技巧总结

来源:互联网 发布:nba季后赛数据排行榜 编辑:程序博客网 时间:2024/05/24 01:27

GridView实用技巧总结

整理:李   2010510~2010524

一、             GridView控件可以绑定的字段控件

a)        BoundField控件:以字符串的方式显示该字段数据。

b)        ButtonField控件:显示一个用户定义的按钮。

c)        CheckField控件:字段值如果是布尔值,显示复选框(checkbox)。

d)        CommandField控件:自动产生一个命令按钮,如编辑(Edit)、更新(Update),以及取消(Cancel)按钮。

e)        HyperLinkField控件:把字段值显示为超级链接(hyperlink)。

f)          ImageField控件:当字段值指向某图片时,则自动显示该图片。

g)        TemplateField控件:允许用户使用模板定制其他控件的外观。

二、             使用GridView控件编辑数据

a)         第一种方法:在当前控件中进行编辑

#region 编辑行

    protected void gvUserList_RowEditing(object sender, GridViewEditEventArgs e)

    {

        gvUserList.EditIndex = e.NewEditIndex;

        BindDataToGridView();

    }

    #endregion

    #region 更新行

    protected void gvUserList_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

      UpdateData();

        gvUserList.EditIndex = -1;

        BindDataToGridView();

    }

    #endregion

    #region 取消编辑

    protected void gvUserList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        gvUserList.EditIndex = -1;

        BindDataToGridView();

    }

#endregion

b)        第二种方法:跳转页面进行编辑

三、             使用GridView控件删除数据

删除数据时弹出对话框询问是否确认删除

方案一:

<a href="javascript:if(confirm('确实要删除吗?'))location='UserList.aspx?&areyou=删除&userId=<%#Eval("UserId") %>'">删除</a>

方案二:

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 + "/"?')");

            }

        }

}

四、             GridView控件的嵌套

a)         两层嵌套

要点:找到被嵌套的控件

DropDownList ddl = e.Row.FindControl("ddlName") as DropDownList;

b)        三层(多层)嵌套

public partial class Manager_CommentList : System.Web.UI.Page

{

    Common com = new Common();

    CommentDAL cDal = new CommentDAL();

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if(!IsPostBack)

        {

        com.BindDataToDataList(dlArticle, cDal.GetArticles());

        }

        Master.Page.Title = "评论列表";

    }

 

    #region 最外层的DataList绑定事件

    /// <summary>

    /// 最外层的DataList

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void dlArticle_ItemDataBound(object sender, DataListItemEventArgs e)

    {

        //获取嵌套的DataList控件

        DataList dl = e.Item.FindControl("dlComment") as DataList;

 

        //获取DataList当前绑定项目的主键

        int articleId = int.Parse(dlArticle.DataKeys[e.Item.ItemIndex].ToString());

       

        com.BindDataToDataList(dl, cDal.GetCommentByArticleId(articleId));

    }

    #endregion

 

    #region 审核状态转换

    public string ConvertToStr(int state)

    {

        if (state == 1)

        {

            return "<img src=/"../images/admin/true.jpg/" style=/"float:left;/"><p style=/"color:green;/">已审核</p>";

        }

        else

        {

            return "<img src=/"../images/admin/false.jpg/" style=/"float:left;/"><p style=/"color:red;/">未审核</p>";

        }

    }

    #endregion

 

    #region 修改审核状态(嵌套三层的控件的控制)

    protected void cboxUpState_CheckedChanged(object sender, EventArgs e)

    {

        CheckBox cboxUpState=sender as CheckBox;

 

        int commentId=int.Parse(cboxUpState.Attributes["commentId"].ToString());

 

        if (cboxUpState.Checked)

        {

            cDal.UpdateCommentStateById(commentId,1);

        }

        else

        {

            cDal.UpdateCommentStateById(commentId,0);

        }

        com.BindDataToDataList(dlArticle, cDal.GetArticles());

    }

    #endregion

 

    #region 绑定CheckBox的审核状态(嵌套两层的控件控制)

    protected void dlComment_ItemDataBound(object sender, DataListItemEventArgs e)

    {

 

        CheckBox cbox = e.Item.FindControl("cboxUpState") as CheckBox;

       

        DataList dl = cbox.Parent.Parent as DataList;

 

        //CheckBox添加一个属性用来保存当前行的Id

        cbox.Attributes.Add("commentId", dl.DataKeys[e.Item.ItemIndex].ToString());

 

        int commentId = int.Parse(dl.DataKeys[e.Item.ItemIndex].ToString());

 

        int state = int.Parse(cDal.GetCommentById(commentId).Rows[0][3].ToString());

 

        if (state == 1)

        {

            cbox.Checked = true;

        }

        else

        {

            cbox.Checked = false;

        }

}

#endregion

五、             GridView控件获取当前行数据的主键

a)        使用GridView控件的DataKeyNames属性

要点一:GridView控件的DataKeyNames属性赋值(可以是多个值)

       绑定一个字段的情况:

              前台:DataKeyNames=”Field”

              后台:GridView1.DataKeys[e.Row.RowIndex].Value.ToString();

       绑定多个字段的情况:

              前台:DataKeyNames=”Field1Name,Field2Name”

              后台:GridView1.DataKeys[e.Row.RowIndex].Values[0].ToString();

GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

或者:

GridView1.DataKeys[e.Row.RowIndex].Values[Field1Name].ToString();

GridView1.DataKeys[e.Row.RowIndex].Values[Field2Name].ToString();

要点二:在不同的事件中获得DataKeyNames的值的方式

//编辑事件

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        //不能直接获取当前行的主键

    }

    //更新事件

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

        //获取当前行的索引(主键)

        int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

        Label1.Text =id.ToString();

    }

    //取消事件

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        BindDataToGridView();

        Label1.Text ="文章类型Id"+ GridView1.DataKeys[e.RowIndex].Values[0].ToString();

        Label1.Text += "父类型Id" + GridView1.DataKeys[e.RowIndex].Values[1].ToString();

    }

    //删除事件

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

int id = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

}

//行绑定事件

#region 绑定行事件

    protected void gvArticleSortList_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        //判断GridView为编辑状态的方法

        if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)

        {

            lbMessage.Text = gvArticleSortList.DataKeys[e.Row.RowIndex].Value.ToString();

        }

    }

    #endregion

b)        使用控件的CommandArgument属性

要点一:了解GridViewRowCommand事件


在单击 GridView 控件中的按钮时,将引发 RowCommand 事件。

尽管单击上表中所列出的按钮时将引发 RowCommand 事件,但仍建议您使用该表中列出的事件来执行该操作。

GridViewCommandEventArgs 对象将传递给事件处理方法,以便可以确定被单击按钮的命令名和命令参数。GridViewCommandEventArgs 类未包含一个用于指示单击按钮所在行的属性。如果需要知道哪个行引发了事件,请使用 CommandArgument 属性将行的索引传给事件处理方法。

CommandName获取或设置一个字符串,该字符串表示当单击 System.Web.UI.WebControls..::.ButtonColumn 对象中的按钮时要执行的命令。

CommandSourceSystem..::.Object 类的一个实例,它表示命令源。使用 CommandSource 属性访问表示命令源的对象的属性。如果是 GridViewCommandEventArgs 对象,命令源为包含用户单击的按钮的 GridView 控件。

NamingContainer:服务器控件的命名容器。

ASP.NET Web 应用程序的每一页均包含控件的层次结构。此层次结构与控件是否生成用户可见的 UI 无关。给定控件的命名容器是层次结构中该控件之上的父控件,此父控件实现 INamingContainer 接口。实现此接口的服务器控件为其子服务器控件的 ID 属性值创建唯一的命名空间。

当针对列表 Web 服务器控件(如 Repeater DataList 服务器控件)进行数据绑定时,为服务器控件创建唯一的命名空间尤其重要。当数据源中的多个项创建服务器控件的多个实例,且该服务器控件是重复控件的子级时,命名容器确保这些子控件的每个实例具有不冲突的 UniqueID 属性值。页的默认命名容器是请求该页时生成的 Page 类的实例。

要点二:控件的Command事件

 

c)         最古老的隐藏列方式

要点:设置隐藏列(直接在控件属性中设置visible属性不可以,因为程序先执行Init事件后执行DataBind事件,隐藏后,控件将无法获得隐藏列的值)

       解决方案一:

              protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

         {

              e.Row.Cells[2].Visible = false;

     }

       解决方案二:

CSS样式中设置:.hidden{display:none;}

          <asp:BoundField DataField="SortId" HeaderText="类型Id">

                <HeaderStyle CssClass="hidden" />

                <ItemStyle CssClass="hidden" />

                <FooterStyle CssClass="hidden" />

    </asp:BoundField>

六、             GridView控件数据的全选

//全选

    protected void cboxSelectAll_CheckedChanged(object sender, EventArgs e)

    {

        CheckBox cboxSelectAll=gvUserList.HeaderRow.FindControl("cboxSelectAll") as CheckBox;

        foreach (GridViewRow gvr in gvUserList.Rows)

        {

            CheckBox cbox = gvr.FindControl("cboxSelected") as CheckBox;

            cbox.Checked = cboxSelectAll.Checked;

        }

 }

七、             GridView控件数据的反选

//反选

    protected void lbtnUnSelect_Click(object sender, EventArgs e)

    {

        CheckBox cboxSelectAll = gvUserList.HeaderRow.FindControl("cboxSelectAll") as CheckBox;

        cboxSelectAll.Checked = false;

        foreach (GridViewRow gvr in gvUserList.Rows)

        {

            CheckBox cbox = gvr.FindControl("cboxSelected") as CheckBox;

            cbox.Checked = !cbox.Checked;

        }

  }

八、             GridView控件数据的批量删除

//批量删除

    protected void lbtnDelSelected_Click(object sender, EventArgs e)

    {

        try

        {

            int count = 0;

            foreach (GridViewRow gvr in gvUserList.Rows)

            {

                CheckBox cbox = gvr.FindControl("cboxSelected") as CheckBox;

                if (cbox.Checked)

                {

                    int userId = int.Parse(gvUserList.DataKeys[gvr.RowIndex].Value.ToString());

                    uDAL.DeleteUser(userId);

                    count++;

                }

            }

            lbMessage.Text = "您已成功删除" + count + "条数据!";

            BindDataToGridView();

        }

        catch(Exception ex)

        {

            lbMessage.Text = "出错了!"+ex.Message;

        }

  }

九、             GridView控件数据的正反双向排序

第一步:设置GridviewAllowSorting属性值为true,即允许排序

第二步:为要排序的列加上SortExpression属性,其值为绑定的字段

第三步:添加Sorting事件

       //排序事件

    protected void gvUserList_Sorting(object sender, GridViewSortEventArgs e)

    {

        string sortExpression = e.SortExpression; //排序表达式

        string sortDirection = "ASC";//排序方式

        if (sortExpression== gvUserList.Attributes["SortExpression"])

        {

            sortDirection = (gvUserList.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");

        }

        gvUserList.Attributes["SortExpression"]=sortExpression;

        gvUserList.Attributes["SortDirection"] = sortDirection;

        SortGridView(sortExpression, sortDirection);

    }

    //排序视图

    public void SortGridView(string sortExpresstion,string sortDirection)

    {

        DataView dv = new DataView(uDAL.GetUsers());

        dv.Sort = sortExpresstion +" "+sortDirection;

        gvUserList.DataSource = dv;

        gvUserList.DataBind();

}

十、             GridView控件数据的分页

解决方案一:使用Gridview自带的分页功能

       第一步:设置GrdView控件的AllowPaging属性为true

       第二步:设置GrdView控件的PageSize属性为 任意数值(默认为10);

       第三步:GrdView控件的PageSetting->ModeNumeric等(默认为Numeric)该属性为分页样式;

       第四步:定义PageIndexChanging事件

//页面更改事件

    protected void gvUserList_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

        gvUserList.PageIndex = e.NewPageIndex;

        BindDataToGridView();

 }

解决方案二:简单自定义分页

#region 分页信息

    public void PageInfo()

    {

        lbPageCount.Text = gvUserList.PageCount.ToString();

        lbCurrentPage.Text = (gvUserList.PageIndex + 1).ToString();

        lbPageSize.Text = gvUserList.PageSize.ToString();

        ddlPageSize.Items.Clear();

        int count = ((DataTable)gvUserList.DataSource).Rows.Count;

        for (int i = 1; i < count + 1; i++)

        {

            ddlPageSize.Items.Add(i.ToString());

        }

    }

    #endregion

    //首页

    protected void lbtnFirstPage_Click(object sender, EventArgs e)

    {

        gvUserList.PageIndex = 0;

        BindDataToGridView();

    }

    //尾页

    protected void lbtnLastPage_Click(object sender, EventArgs e)

    {

        gvUserList.PageIndex = gvUserList.PageCount - 1;

        BindDataToGridView();

    }

    //上一页

    protected void lbtnPrePage_Click(object sender, EventArgs e)

    {

        if (gvUserList.PageIndex != 0)

        {

            gvUserList.PageIndex = gvUserList.PageIndex - 1;

            BindDataToGridView();

        }

    }

    //下一页

    protected void lbtnNextPage_Click(object sender, EventArgs e)

    {

        gvUserList.PageIndex = gvUserList.PageIndex + 1;

        BindDataToGridView();

    }

    //每页显示的记录条数

    protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)

    {

        gvUserList.PageSize = int.Parse(ddlPageSize.Text);

        BindDataToGridView();

 }

解决方案三:第三方分页控件

解决方案四:自定义分页控件

解决方案五:存储过程分页(效率最高的)

十一、      GridView控件数据导入Excel/Excel数据导入GridView控件

a)         GridView控件数据导入Excel

b)        Excel数据导入GridView控件

十二、      GridView控件自定义样式

a)         高亮显示特殊数据

b)        鼠标滑过某一行时改变行样式


原创粉丝点击