溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

gridview控件怎么在asp.net中使用

發(fā)布時(shí)間:2021-01-15 15:35:39 來源:億速云 閱讀:261 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹gridview控件怎么在asp.net中使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

gridview是asp.net常用的顯示數(shù)據(jù)控件,對(duì)于.net開發(fā)人員來說應(yīng)該是非常的熟悉了。gridview自帶有許多功能,包括分頁,排序等等,但是作為一個(gè).net開發(fā)人員來說熟練掌握利用存儲(chǔ)過程分頁或者第三方自定義分頁十分重要,這不僅是項(xiàng)目的需要,也是我們經(jīng)驗(yàn)?zāi)芰Φ奶崾荆旅嫖揖蛠碇v利用存儲(chǔ)過程分頁實(shí)現(xiàn)綁定gridview

1、執(zhí)行存儲(chǔ)過程

        網(wǎng)上有許多sql分頁存儲(chǔ)過程的例子,但是你會(huì)發(fā)現(xiàn)其中有許多一部分是不能用的,例如有些使用in或者not in來分頁效率非常的低,有些sp可以分頁但是擴(kuò)展型非常差,有些效率也比較高,但是不能返回查詢記錄總數(shù),

例如下面的這個(gè)分頁,盡管比較簡(jiǎn)單,但是用not in來分頁效率比較低,且查詢表已經(jīng)固定死了,無法擴(kuò)展,其實(shí)是個(gè)失敗的分頁

CREATE PROCEDURE GetProductsByPage 
@PageNumber int, 
@PageSize int
AS
declare @sql nvarchar(4000) 
set @sql = 'select top ' + Convert(varchar, @PageSize) + ' * from test where id not in (select top ' + Convert(varchar, (@PageNumber - 1) * @PageSize) + ' id from test)'
exec sp_executesql @sql
GO

 綜上我覺得這個(gè)分頁總體上來說比較好的效率也非常的高且分頁只需要執(zhí)行一次sp,分頁支持多表多標(biāo)間查詢

ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber]
 (
  @tbName VARCHAR(255),   --表名
  @tbGetFields VARCHAR(1000)= '*',--返回字段
  @OrderfldName VARCHAR(255),  --排序的字段名
  @PageSize INT=20,    --頁尺寸
  @PageIndex INT=1,    --頁碼
  @OrderType bit = 0,    --0升序,非0降序
  @strWhere VARCHAR(1000)='',  --查詢條件
  @TotalCount INT OUTPUT   --返回總記錄數(shù)
 )
 AS
 -- =============================================
 -- Author:  allen (liyuxin)
 -- Create date: 2012-03-30
 -- Description: 分頁存儲(chǔ)過程(支持多表連接查詢)
 -- Modify [1]: 2012-03-30
 -- =============================================
 BEGIN
  DECLARE @strSql VARCHAR(5000) --主語句
  DECLARE @strSqlCount NVARCHAR(500)--查詢記錄總數(shù)主語句
  DECLARE @strOrder VARCHAR(300) -- 排序類型
  
  --------------總記錄數(shù)---------------
  IF ISNULL(@strWhere,'') <>''
   SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName + ' where 1=1 '+ @strWhere
  ELSE SET @strSqlCount='Select @TotalCout=count(*) from ' + @tbName
   
  exec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output
  --------------分頁------------
  IF @PageIndex <= 0 SET @PageIndex = 1
  
  IF(@OrderType<>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC '
  ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC '
  
  SET @strSql='SELECT * FROM 
  (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb 
  WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)
  
  exec(@strSql)
  SELECT @TotalCount
 END

2  、封裝c#調(diào)用語句

      我們總是習(xí)慣上對(duì)代碼進(jìn)行封裝,這樣可以提高代碼的閱讀效率,維護(hù)起來也更加方便,養(yǎng)成良好的封裝代碼習(xí)慣,我們就從初級(jí)步入了中級(jí),其實(shí)這只是個(gè)習(xí)慣而已

public static class PageHelper
 {
  /// <summary>
  /// 分頁數(shù)據(jù)
  /// </summary>
  /// <param name="TableName">表明</param>
  /// <param name="RetureFields">返回字段</param>
  /// <param name="strWhere">條件</param>
  /// <param name="PageSize">每頁記錄數(shù)</param>
  /// <param name="CurPage">當(dāng)前頁數(shù)</param>
  /// <param name="RowCount">總記錄數(shù)</param>
  /// <param name="sortField">排序字段</param>
  /// <returns></returns>
 public static DataTable GetPageList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, int OrderType, string strWhere, out int TotalCount)
  {
   SqlCommand cmd = new SqlCommand("Proc_SqlPageByRownumber");//存儲(chǔ)過程名稱
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.AddWithValue("@tbName", tbName);//表名稱
   cmd.Parameters.AddWithValue("@tbGetFields", tbGetFields);//要顯示的字段名(不要加Select)
   cmd.Parameters.AddWithValue("@OrderfldName", OrderFldName);//排序索引字段名
   cmd.Parameters.AddWithValue("@PageIndex", PageIndex);//當(dāng)前第幾頁,頁碼
   cmd.Parameters.AddWithValue("@PageSize", PageSize);//每頁顯示的數(shù)據(jù)條數(shù)
   cmd.Parameters.AddWithValue("@OrderType", OrderType);//設(shè)置排序類型,非0值則降序
   cmd.Parameters.AddWithValue("@strWhere", strWhere);//查詢條件,不要加where
   cmd.Parameters.Add(new SqlParameter("@TotalCount", SqlDbType.Int));
   cmd.Parameters["@TotalCount"].Direction = ParameterDirection.Output;
   DataTable dt = RunProcedureCmd(cmd);
   TotalCount = Convert.ToInt32(cmd.Parameters["@TotalCount"].Value.ToString());//返回的總頁數(shù)
   return dt;
  }
 
  /// <summary>
  /// 執(zhí)行存儲(chǔ)過程,返回DataTable
  /// </summary>
  /// <param name="cmd"></param>
  /// <returns></returns>
  public static DataTable RunProcedureCmd(SqlCommand cmd)
  {
   DataTable result = new DataTable();
   string connectionString = ConfigurationManager.AppSettings["CONNSTRING"].ToString();
   SqlConnection conn = new SqlConnection(connectionString);//你自己的鏈接字符串
   try
   {
    if ((conn.State == ConnectionState.Closed))
    {
     conn.Open();
    }
    cmd.Connection = conn;
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(result);
    da.Dispose();
    conn.Close();
    conn.Dispose();
 
    return result;
   }
   catch (Exception ex)
   {
    conn.Close();
    conn.Dispose();
    throw ex;
   }
  } 
 }

3、 gridview利用第三方插件實(shí)現(xiàn)分頁

分頁現(xiàn)在比較流行的插件是aspnetpager,這是一個(gè)比較成熟的插件,網(wǎng)上也有許多的例子。

1 )、下載aspnetpager插件,然后右鍵引用。

2 )、 打開工具箱,在選項(xiàng)卡上右鍵選擇項(xiàng)導(dǎo)入插件

3 )、拖控件到頁面,設(shè)置控件的屬性

后臺(tái)代碼

protected void Page_Load(object sender, EventArgs e)
  {
   if (!IsPostBack)
   {
    GridViewBind("");
   }
  }
 
  private void GridViewBind(string sqlWhere)
  {
   int TotalCount;
   DataTable dt = bll.GetList("stu_score", "code,name,beginTime,endTime,score", "id", this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex, 1,sqlWhere, out TotalCount);
   this.AspNetPager1.RecordCount = TotalCount;
   this.GridView1.DataSource = dt;
   this.GridView1.DataBind();
   this.AspNetPager1.CustomInfoHTML = string.Format("當(dāng)前第{0}/{1}頁 共{2}條記錄 每頁{3}條", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });  
  }
 
  
//GridView高亮行顯示 
  protectedvoid GridView1_RowDataBound1(object sender, GridViewRowEventArgs e) 
   { 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
      e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor,this.style.backgroundColor='#C7DEF3'"); 
     e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); 
    } 
   }

前臺(tái)代碼

<table width="100%">
 <tr>
  <td >
   beginTime:<asp:TextBox ID="txtBeginTime" runat="server"></asp:TextBox>
   endTime:<asp:TextBox ID="txtEndTime" name="mydate" runat="server"></asp:TextBox>
  </td>
  <td >
   <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"
    class="ui-button ui-widget ui-state-default ui-corner-all"></asp:Button> 
   <asp:Button ID="btnAdd" runat="server" Text="Create" OnClientClick="javascript:return false;" />
  </td>
 </tr>
 <tr>
  <td colspan="2" >
   <asp:GridView ID="GridView1" runat="server" Width="100%" CellPadding="2" CssClass="GridViewStyle"
    CellSpacing="2" AutoGenerateColumns="False">
    <Columns>
     <asp:BoundField DataField="name" HeaderText="name" />
     <asp:BoundField DataField="code" HeaderText="code" />
     <asp:BoundField DataField="beginTime" HeaderText="beginTime" />
     <asp:BoundField DataField="endTime" HeaderText="endTime" />
     <asp:BoundField DataField="score" HeaderText="score" />
    </Columns>
    <FooterStyle CssClass="GridViewFooterStyle" />
    <RowStyle CssClass="GridViewRowStyle" />
    <SelectedRowStyle CssClass="GridViewSelectedRowStyle" />
    <PagerStyle CssClass="GridViewPagerStyle" />
    <AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
    <HeaderStyle CssClass="GridViewHeaderStyle" />
   </asp:GridView>
  </td>
 </tr>
 <tr>
  <td colspan="2">
   <webdiyer:AspNetPager ID="AspNetPager1" runat="server" CssClass="paginator" CurrentPageButtonClass="cpb"
    OnPageChanged="AspNetPager1_PageChanged" PageSize="5" FirstPageText="首頁" LastPageText="尾頁"
    NextPageText="下一頁" PrevPageText="上一頁" CustomInfoHTML="共%RecordCount%條,第%CurrentPageIndex%頁 /共%PageCount% 頁"
    CustomInfoSectionWidth="30%" ShowCustomInfoSection="Right">
   </webdiyer:AspNetPager>
  </td>
 </tr>
</table>

4 、當(dāng)然你可以對(duì)你的gridview進(jìn)行樣式調(diào)整,新建gridviewSY.css

.GridViewStyle
{ 
 border-right: 2px solid #A7A6AA;
 border-bottom: 2px solid #A7A6AA;
 border-left: 2px solid white;
 border-top: 2px solid white;
 padding: 4px;
}
.GridViewStyle a
{
 color: #FFFFFF;
}
 
.GridViewHeaderStyle th
{
 border-left: 1px solid #EBE9ED;
 border-right: 1px solid #EBE9ED;
}
 
.GridViewHeaderStyle
{
 background-color: #5D7B9D;
 font-weight: bold;
 color: White;
}
 
.GridViewFooterStyle
{
 background-color: #5D7B9D;
 font-weight: bold;
 color: White;
}
 
.GridViewRowStyle
{
 background-color: #F7F6F3;
 color: #333333;
}
 
.GridViewAlternatingRowStyle
{
 background-color: #FFFFFF;
 color: #284775;
}
 
.GridViewRowStyle td, .GridViewAlternatingRowStyle td
{
 border: 1px solid #EBE9ED;
}
 
.GridViewSelectedRowStyle
{
 background-color: #E2DED6;
 font-weight: bold;
 color: #333333;
}
 
.GridViewPagerStyle
{
 background-color: #284775;
 color: #FFFFFF;
}
 
.GridViewPagerStyle table /* to center the paging links*/
{
 margin: 0 auto 0 auto;
分頁控件也添加樣式,當(dāng)然gridview樣式和分頁樣式在同一個(gè)css中了

.paginator { font: 11px Arial, Helvetica, sans-serif;padding:10px 20px
 
10px 0; margin: 0px;}
.paginator a {padding: 1px 6px; border: solid 1px #ddd; background:
 
#fff; text-decoration: none;margin-right:2px}
.paginator a:visited {padding: 1px 6px; border: solid 1px #ddd;
 
background: #fff; text-decoration: none;}
.paginator .cpb {padding: 1px 6px;font-weight: bold; font-size:
 
13px;border:none}
.paginator a:hover {color: #fff; background: #ffa501;border-
 
color:#ffa501;text-decoration: none;}

頁面最總結(jié)果顯示樣式,

 gridview控件怎么在asp.net中使用

接下來我們給時(shí)間添加樣式,給時(shí)間添加樣式普遍選擇的是datePicker插件,導(dǎo)入控件所用的js和css

<script src="jquery-ui-1.9.2.custom/js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.widget.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.core.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.datepicker.js" type="text/javascript"></script><link href="jquery-ui-1.9.2.custom/development-bundle/themes/ui-lightness/jquery.ui.all.css" rel="stylesheet" type="text/css" />

默認(rèn)時(shí)間插件顯示的是英文,我們給他漢化

新建initdatepicker_cn.js

function initdatepicker_cn() {
 $.datepicker.regional['zh-CN'] = {
  clearText: '清除',
  clearStatus: '清除已選日期',
  closeText: '關(guān)閉',
  closeStatus: '不改變當(dāng)前選擇',
  prevText: '<上月',
  prevStatus: '顯示上月',
  prevBigText: '<<',
  prevBigStatus: '顯示上一年',
  nextText: '下月>',
  nextStatus: '顯示下月',
  nextBigText: '>>',
  nextBigStatus: '顯示下一年',
  currentText: '今天',
  currentStatus: '顯示本月',
  monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
  monthStatus: '選擇月份',
  yearStatus: '選擇年份',
  weekHeader: '周',
  weekStatus: '年內(nèi)周次',
  dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
  dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
  dayStatus: '設(shè)置 DD 為一周起始',
  dateStatus: '選擇 m月 d日,DD',
  dateFormat: 'yy-mm-dd',
  firstDay: 1,
  initStatus: '請(qǐng)選擇日期',
  isRTL: false
 };
 $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
}

  前臺(tái)頁面添加jquery腳本,當(dāng)然MainContent_txtBeginTime是你時(shí)間標(biāo)簽的id,有時(shí)候你可能顯示不出來,不要著急右鍵查看源文件就會(huì)發(fā)現(xiàn)控件的id和html標(biāo)簽的id不一樣,我們一定要選擇標(biāo)簽的id

<script type="text/javascript">
 
 jQuery(function () {
 
  initdatepicker_cn();
  $('#MainContent_txtBeginTime').datepicker({ changeMonth: true, changeYear: true });
 });
</script>

關(guān)于gridview控件怎么在asp.net中使用就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI