Asp.net GridView控件使用常用范例

发布时间:2019-09-12编辑:脚本学堂
为大家介绍GridView控件应用的一些例子,包括基本应用、排序、自带分页、显示颜色与删除颜色、Gridview的导出等内容,有兴趣的朋友,可以参考下。

4、自带分页
 

复制代码 代码示例:
#region自带分页
protected void FollowExamInfoGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
 FollowExamInfoGridView.PageIndex = e.NewPageIndex;
 BindFollowExamInfoGridView(Convert.ToInt32(HiddenPersonID.Value));
}
#endregion

5、选中Grid View 的实现
 

复制代码 代码示例:
#region实现选中行
<SelectedRowStyle BackColor="AliceBlue" ForeColor="Gray" />
<asp:CommandField ShowSelectButton="True"/>
if (e.Row.RowType == DataControlRowType.DataRow)
  {
      e.Row.Attributes.Add("onclick", "this.cells[0].childNodes[0].click()");
}
protected void GridViewRegiment_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = GridViewRegiment.SelectedRow;
    int RegimentID = Convert.ToInt32(row.Cells[1].Text);
    Response.Redirect("UpdateRegimentation.aspx?RegimentID=" + RegimentID);
}
#endregion

6、显示颜色和删除
 

复制代码 代码示例:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //int i;
    //for (i = 0; i < GridViewRegiment.Rows.Count; i++)
    //{
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        //当有编辑列时,避免出错,要加的RowState判断
        if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
        {
          ((ImageButton)e.Row.Cells[2].FindControl("IBtndelete")).Attributes.Add("onclick", "javascript:return confirm('你确认要删除:"" + e.Row.Cells[0].Text + ""吗?')");
        }
        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#00A9FF'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E6F5FA'");
      }
    //}
}

7、GridView空的处理
1)、显示无表头的空纪录,EmptyDataText="没有记录"
2)、显示表头的空纪录
 

复制代码 代码示例:
DataTable dt = new DataTable();
  dt = feibf.GetByPersonIDFollowExamInfo(PersonID);  //查询指定人的随访信息记录
    DataView dv = SortBindGrid(dt);
    if (dt.Rows.Count > 0)
    {
      FollowExamInfoGridView.DataSource = dv;
      FollowExamInfoGridView.DataBind();
    }
    else
    {
      //添加新行显示表头
      dt.Rows.Add(dt.NewRow());
      FollowExamInfoGridView.DataSource = dt;
      FollowExamInfoGridView.DataBind();
      //处理新行
      int columnCount = FollowExamInfoGridView.Rows[0].Cells.Count;
      //清除掉该空行的全部单元格
      FollowExamInfoGridView.Rows[0].Cells.Clear();
      //新建单元格对象
      FollowExamInfoGridView.Rows[0].Cells.Add(new TableCell());
      //合并单元格
      FollowExamInfoGridView.Rows[0].Cells[0].ColumnSpan = columnCount;
      //设置单元格提示内容
      FollowExamInfoGridView.Rows[0].Cells[0].Style.Value = "text-align:center";
      FollowExamInfoGridView.Rows[0].Cells[0].Text = "此人无随访信息";
    }