GridView使用初步

(1)RowCommand事件使用

页面:

 <asp:TemplateField HeaderText="用户状态">
          <ItemTemplate>
                <asp:LinkButton runat="server" ID="lnkbtnStatus" CommandArgument='<%# Eval("Id") %>' CommandName="UpStatus" Text='<%# Eval("UserState.Name") %>'></asp:LinkButton>
          </ItemTemplate>
</asp:TemplateField>    

代码:

    //模版列中的按钮也会触发RowCommand事件

    protected void gvMain_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //预留其他命令
        switch (e.CommandName)
        {
            case "UpStatus":
                    UserManager.ModifyUserStatusById(Convert.ToInt32(e.CommandArgument));
                    BindGridView();
                break;
            default:
                break;
        }
    }        

(2)全选

页面:

<asp:TemplateField HeaderText="全选">
         <ItemTemplate>
               <asp:CheckBox runat="server" ID="chkSelect" />
         </ItemTemplate>
        <HeaderTemplate>
              &nbsp;<input id="cbAll" type="checkbox" onclick="GetAllCheckBox(this)" />全选
        </HeaderTemplate>
</asp:TemplateField>

<asp:TemplateField Visible="False">
        <ItemTemplate>
                <asp:Label ID="lblId" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
         </ItemTemplate>
</asp:TemplateField>

<script language="javascript">
function GetAllCheckBox(CheckAll)
{
 var items = document.getElementsByTagName("input");    
 for(i=0; i<items.length;i++)
 {      
   if(items[i].type=="checkbox")
   {
        items[i].checked = CheckAll.checked;
   }
 }
}
</script>

代码:

    protected void btnSure_Click(object sender, EventArgs e)
    {
        string sb =String.Empty;
        for (int i = 0; i < this.gvBooks.Rows.Count; i++)
        {
            CheckBox cb = (gvBooks.Rows[i].FindControl("chkSelect")) as CheckBox;
            if (cb.Checked == true)
            {
                sb += (gvBooks.Rows[i].FindControl("lblId") as Label).Text+",";               
            }
        }
        string catagory = this.ddlCatagory.SelectedItem.Value;    
       if (sb.Length > 0)
        {
            sb = sb.Substring(0, sb.Length - 1);
        }
        DBHelper.ExecuteCommand("update Books set CategoryId=" + catagory + " where id in(" + sb + ")");

}

(3)RowDataBound事件使用

 3.1 鼠标所在行变色、对某些数据列值显示时进行截断处理

    protected void gvBooks_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");

            if (e.Row.Cells[6].Text.Length > 4)
            {
                e.Row.Cells[6].ToolTip = e.Row.Cells[6].Text;
                e.Row.Cells[6].Text = e.Row.Cells[6].Text.Substring(0, 4) + "... ";

            }
        }
    }

3.2 根据条件,设置相应行的前景色(背景色)

            if (e.Row.RowType==DataControlRowType.DataRow)   //判断是否是数据
            {

                DateTime sxrq = Convert.ToDateTime(e.Row.Cells[10].Text);  //有效期字段
                if ((sxrq - DateTime.Today).Days < 180)  //sxrq-当天日期<180天
                {
                    e.Row.ForeColor = System.Drawing.Color.Red;  //设置前景色
                }
            } 

3.3 实现GridView控件中数据自动求和功能

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

   if  (e.Row.RowIndex >= 0)

   {

      sum += Convert.ToInt32(e.Row.Cells[4].Text);

    }

    else if (e.Row.RowType == DataControlRowType.Footer)

    {

      e.Row.Cells[1].Text = "总分为:";

      e.Row.Cells[2].Text = sum.ToString();

      e.Row.Cells[3].Text = "平均分为:";

      e.Row.Cells[4].Text = ((int)(sum / GridView1.Rows.Count)).ToString();

    }

}

3.4 在RowDataBound事件中取值

3.4.1 e.Row.Cells[x].Text

不能取得隐藏列的值

3.4.2 e.Row.Cells[x].FindControl("ControlName")。

用于取得模版列的值

3.4.3 (DataRowView)e.Row.DataItem).Row.ItemArray[x].ToString()。
  此法的核心是e.Row.DataItem,它是GridView的行数据集,为Object类型,将其转化为DataRowView类型后,可以获得更多的操作方法。此数据集表示数据源当前行的全部字段列,ItemArray[x]是当前行全部字段列的数组对象,可以通过索引x获得任意字段值,可以对数据源的全部字段查询。

3.4.4 取主键的值

GridView1.DataKeys[e.Row.RowIndex].Value

3.5 GridView实现删除时弹出确认对话框

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

    }

 

(4)实现删除、自定义删除、编辑功能

删除功能:       

         设置GridView控件的DataKeyNames属性为StudentID。通过GridView智能标记,编辑列,添加CommandField中的“删除”字段,设置HeadText属性。当用户单击“删除”按钮时,会触发RowDeleting和RowDeleted事件,我们通过编写RowDeleting事件处理代码,实现记录删除功能。关键代码如下:

            string sid = GridView1.DataKeys[e.RowIndex].Value.ToString();

            String sql = "delete from StudentScore where StudentID=@StudentID";

            OleDbCommand cmd = new OleDbCommand(sql, conn);

            cmd.Parameters.AddWithValue("@StudentID", sid);//演示sql参数使用

自定义删除: 

     通过GridView智能标记,编辑列,添加ButtonField的字段,设置HeadText属性为“自定义删除”,DataTextField属性为StudentID,DataTextFormatString属性为删除"{0}"的记录,CommandName属性为del。当用户单击ButtonField时,会触发GridView控件的RowCommand事件,其参数e有以下重要属性:

        e.CommandName属性表明哪个按钮被单击

        e.CommandArgument属性表明是哪一行

    可以通过编写RowCommand事件处理代码,实现记录删除。关键代码如下:

 if (e.CommandName == "del")          //判断是哪个按钮

 {

     int rowindex = Convert.ToInt32(e.CommandArgument);  //获取行索引

     string sid = GridView1.DataKeys[rowindex].Value.ToString();

        ----

 }

编辑:

       通过GridView智能标记,编辑列,添加ButtonField的字段,设置HeadText属性为“编辑”,CommandName属性为myedit。当用户单击ButtonField时,同样会触发GridView控件的RowCommand事件,在此事件中编写代码,将当前记录信息在文本框中显示出来,以供用户修改:

        if (e.CommandName == "myedit")

        {

            ViewState["m"] = 1;                           //标志位,表示修改记录

            int rowindex = Convert.ToInt32(e.CommandArgument);  //获取行索引

            GridViewRow row = GridView1.Rows[rowindex];

            lblCaption.Text = "编辑学生成绩";

            txtStudentID.Enabled = false;   //学号不允许更改

            txtStudentID.Text = row.Cells[0].Text;

            txtName.Text = row.Cells[1].Text;

            txtMath.Text = row.Cells[2].Text;

            txtChinese.Text = row.Cells[3].Text;

            txtEnglish.Text = row.Cells[4].Text;

        }

知识点扩展:

当用户单击ButtonField时,会触发GridView控件的RowCommand事件,其参数e.CommandName属性特别值得注意。当一个ButtonField的CommandName是以下预定义值是,会触发特定的事件:

CommandName 值

说明

“Cancel”

取消编辑操作并将 GridView 控件返回为只读模式。引发 RowCancelingEdit 事件。

“Delete”

删除当前记录。引发 RowDeletingRowDeleted 事件。

“Edit”

将当前记录置于编辑模式。引发 RowEditing 事件。

“Page”

执行分页操作。将按钮的 CommandArgument 属性设置为“First”、“Last”、“Next”、“Prev”或页码,以指定要执行的分页操作类型。引发 PageIndexChangingPageIndexChanged 事件。

“Select”

选择当前记录。引发 SelectedIndexChangingSelectedIndexChanged 事件。

“Sort”

GridView 控件进行排序。引发 SortingSorted 事件。

“Update”

更新数据源中的当前记录。引发 RowUpdatingRowUpdated 事件。

模板列中的按钮的CommandName如果是上述预定义值时,也会触发特定的事件。如下面的按钮同样会触发RowDeleting事件:

<asp:TemplateField HeaderText="删除" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" OnClientClick="return confirm('确定删除吗?')" Text="删除"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

 

(5)排序

       首先,设置GridView的AllowSorting="True",将导致用户单击GridView自动生成列的标题时,触发Sorting事件;或者,直接调用Sort()方法,也会触发Sorting事件,如:

        //在此处会激发GridView的Sorting事件,第一个参数将被传送到Sorting事件的参数e中
        GridView1.Sort("ClientName", SortDirection.Ascending);

        在Sorting事件中以数据源进行排序,然后重新绑定数据并显示,如:

       //获取要显示的记录集
        List<ClientInfo> clients = GetAllClients();
        //判断是哪个控件引发的排序
        switch (e.SortExpression)
        {
            case "ClientName":
                clients.Sort(CompareByClientName); //数据源排序
                break;
            ------
        }
        //重新绑定数据并显示
        GridView1.DataSource = clients;
        GridView1.DataBind();

   使用DataView进行排序的方法如下:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["SortOrder"] = "ASC";//排序顺序
                ViewState["SortField"] = "GradeId";//排序字段
                Bind();
            }
        }

        public void Bind()
        {
            DataView view = bll.GetAllGrade().DefaultView;
            view.Sort = ViewState["SortField"] + " " + ViewState["SortOrder"];
            GridView1.DataSource = view;
            GridView1.DataBind();
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (e.SortExpression.ToString() == ViewState["SortField"].ToString())
            {
                if(ViewState["SortOrder"].ToString() == "Asc")
                {
                    ViewState["SortOrder"] ="Desc";
                }
                else
                   ViewState["SortOrder"] ="Asc";
            }
            else
            {
                ViewState["SortField"] = e.SortExpression;
            }
            Bind();
        }

 

(6)GridView显示行的序号:
<asp:GridView ID="GridView1" runat="server">
    <Columns>       
        <asp:TemplateField>           
            <ItemTemplate>               
                <%#Container.DataItemIndex+1 %>               
            </ItemTemplate>       
        </asp:TemplateField>   
    </Columns>
</asp:GridView>

(7)GridView各个事件中获取主键值

在 GridView1_RowDataBound中获取主键的值
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
     int index = GridView1.DataKeys[e.Row.RowIndex].Value;
}

如果DataKeyNames属性是多个字段,如DataKeyNames="SubjectID,Mode",则获取键值的代码如下

VoteView.DataKeys[e.Row.RowIndex].Values["Mode"].ToString()

//删除事件
在 GridView1_RowDeleting中获取主键的值
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
     int index=GridView1.DataKeys[e.RowIndex].Value;
}

如果是复合主键,在前台页面指定复合主键DataKeyNames="sno,cno",然后用下面的代码获取复合主键

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    //string sno = GridView1.Rows[e.RowIndex].Cells[0].Text;
    //string cno = GridView1.Rows[e.RowIndex].Cells[2].Text;
    string sno = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
    string cno = GridView1.DataKeys[e.RowIndex].Values[1].ToString();
    Response.Write(sno + "," + cno);

//分页事件
在 GridView1_PageIndexChanging中获取主键的值
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     int index=GridView1.DataKeys[e.NewPageIndex].Value;
}

在 GridView1_RowCommand中获取主键的值:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
     int index = GridView1.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
}

在 GridView1_RowEditing中获取主键的值
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
     int index = GridView1.DataKeys[e.NewEditIndex].Value;
}

在 GridView1_RowUpdating中获取主键的值
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
      int index = GridView1.DataKeys[e.RowIndex].Value;
}

(8)分页(GridView自带的分页功能)

设置属性:

   AllowPaging="True"

   PageSize="2"

处理PageIndexChanging事件:

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {  
            GridView1.PageIndex= e.NewPageIndex;
            Bind();
        }

(9)模版列使用

<asp:TemplateField HeaderText="用户操作">
    <ItemTemplate>
        <asp:ImageButton ID="ImageButton1" runat="server"
            CommandArgument='<%# Eval("id") %>' CommandName="myedit"
            ImageUrl="~/images/31.gif" />
        <asp:ImageButton ID="ImageButton2" runat="server"
            CommandArgument='<%# Eval("id") %>' CommandName="mydel"
            ImageUrl="~/images/061.GIF" />
        <a href='ContactEdit.aspx?id=<%#Eval("id")%>'>编辑</a>
        <a href='ContactEdit.aspx?id=<%#((System.Data.DataRowView)(Container.DataItem))["id"]%>'>编辑</a>
    </ItemTemplate>
</asp:TemplateField> 

Eval通过反射来完成,会损失性能,可以用<%#((System.Data.DataRowView)(Container.DataItem))["id"]%>来提升性能。

protected void gvContact_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "myedit")
    {
        Response.Write(e.CommandArgument.ToString());
    }
    else
        if(e.CommandName=="mydel")
        {
            Response.Write(e.CommandArgument.ToString());
        }

posted @ 2011-05-03 16:06  zhouhb  阅读(2421)  评论(0编辑  收藏  举报