2016-08-19 70 views
1

我在ASP.NET C#中使用DataGrid。我想限制和控制顯示的項目數DataGrid(我被迫使用這個控制器)。限制asp.net中的datagrid項目c#

我知道我們可以控制使用sql查詢中使用

  1. AllowPaging = "TRUE"按頁
  2. 限制DataSource,然後結合(DataBind())它。

但我不想要。我想運行sql查詢一次並獲取所有數據,然後根據需要我必須能夠顯示前10或20個項目。

這是最好,如果我能在代碼中做到這一點

  1. 後面。
  2. 沒有頁面重載,如果我從10

增加項目大小到30任何一種單挑在正確的道路讚賞

+0

你允許使用AJAX? – Ramki

+0

如果你在你的項目中使用'JQuery'。此鏈接可能對您有所幫助:http://www.aspsnippets.com/Articles/Implement-Infinite-Scroll-Endless-Scroll-in-ASPNet-using-jQuery-AJAX.aspx –

+0

@Ramki是我可以 – saai

回答

1

這裏有兩個選項來考慮。第一個使用DataTableLinq獲得頂部x行。

DataTable dt = yourDataTableSource; 
GridView1.DataSource = dt.AsEnumerable().Take(5).CopyToDataTable(); 
//Linq example with sorting added 
//GridView1.DataSource = dt.AsEnumerable().OrderBy(x => x["columnName"]).Take(5).CopyToDataTable(); 
GridView1.DataBind(); 

或者您可以使用通常在.aspx頁面上找到的相同屬性。只有這些在現在的代碼背後設置,你仍然可以使用你當前的數據源。

GridView1.PageSize = 5; 
GridView1.AllowPaging = true; 
GridView1.PagerSettings.Visible = false; 
GridView1.DataBind(); 

或爲DataGrid

DataGrid1.PageSize = 10; 
DataGrid1.AllowPaging = true; 
DataGrid1.PagerStyle.Visible = false; 
DataGrid1.DataBind(); 

,並完成你的問題,這裏是一個小例子,讓你開始的如何獲得無需刷新頁面顯示的項目的變化。

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> 
    <!-- a ScriptManager is required when working with UpdatePanels --> 

    <asp:UpdatePanel ID="UpdatePanel1" runat="server"> 
     <ContentTemplate> 

      <asp:GridView ID="GridView1" runat="server"></asp:GridView> 
      <br /> 
      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> 
       <asp:ListItem Text="5 rows" Value="5"></asp:ListItem> 
       <asp:ListItem Text="10 rows" Value="10"></asp:ListItem> 
       <asp:ListItem Text="15 rows" Value="15"></asp:ListItem> 
      </asp:DropDownList> 

     </ContentTemplate> 
    </asp:UpdatePanel> 

後面的代碼:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      DataTable dt = yourDataTableSource; 
      GridView1.DataSource = dt; 
      GridView1.PageSize = 10; 
      GridView1.AllowPaging = true; 
      GridView1.PagerSettings.Visible = false; 
      GridView1.DataBind(); 

      ViewState["GridView1Content"] = dt; 
     } 
    } 

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     int pageSize = 10; 

     //always do validation with user input... 
     try 
     { 
      pageSize = Convert.ToInt32(DropDownList1.SelectedValue); 
     } 
     catch 
     { 
     } 

     GridView1.PageSize = pageSize; 
     GridView1.DataSource = ViewState["GridView1Content"] as DataTable; 
     GridView1.DataBind(); 
    } 
+0

我'米給你+1,但是,我明確提到,我不得不使用Datagrid,而不是GridView。儘管它們在某些方面相似,但它們具有不同的特徵。我已經提到過我不想分頁 – saai

+0

你可以同時使用我提到的一個DataGrid的兩個選項。通過設置'DataGrid1.PagerStyle.Visible = false;'(而不是'GridView1.PagerSettings.Visible = false;'爲GrideViews),用戶不會看到分頁。 – VDWWD

+0

謝謝,這很有幫助,但在您的示例中,您將根據大小綁定datasurce,當大小增加時,速度很慢。我認爲如果在沒有約束力的情況下追加下一組將會是更好的解決方案。我怎樣才能將值附加到'DataGrid'上 – saai

1

我來到這樣的事情,但我使用的GridView,當頁面來通過服務器端頁面處理將其遷移到數據表。

這是一個通用圖層。修改它以滿足你的需要!

Here's解析器我得到:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Reflection; 
using System.Web; 

namespace iMax_WeSite.app.Objects.DataTables 
{ 
    public class DataTable 
    { 
     public DataTable() 
     { 
     } 
     public int sEcho { get; set; } 
     public int iTotalRecords { get; set; } 
     public int iTotalDisplayRecords { get; set; } 
     public string iTotalValue { get; set; } //Somatoria total do valor 
     public string iTotalFilteredValue { get; set; } //Somatoria parcial do valor 
     public List<List<string>> aaData { get; set; } 
     public string sColumns { get; set; } 

     public void Import(string[] properties) 
     { 
      sColumns = string.Empty; 
      for (int i = 0; i < properties.Length; i++) 
      { 
       sColumns += properties[i]; 
       if (i < properties.Length - 1) 
        sColumns += ","; 
      } 
     } 
    } 
    public class DataTableParser<T> 
    { 
     private const string INDIVIDUAL_SEARCH_KEY_PREFIX = "sSearch_"; 
     private const string INDIVIDUAL_SORT_KEY_PREFIX = "iSortCol_"; 
     private const string INDIVIDUAL_SORT_DIRECTION_KEY_PREFIX = "sSortDir_"; 
     private const string DISPLAY_START = "iDisplayStart"; 
     private const string DISPLAY_LENGTH = "iDisplayLength"; 
     private const string ECHO = "sEcho"; 
     private const string SEARCH = "sSearch"; 
     private const string ASCENDING_SORT = "asc"; 
     private IQueryable<T> _queriable; 
     private readonly Dictionary<string, object> _tableParams; 
     private readonly Type _type; 
     private readonly System.Reflection.PropertyInfo[] _properties; 
     public DataTableParser(Dictionary<string, object> tableParams, IQueryable<T> queriable) 
     { 
      _queriable = queriable; 
      _tableParams = tableParams; 
      _type = typeof(T); 
      _properties = _type.GetProperties(); 
     } 

     public DataTable Parse() 
     { 
      var list = new DataTable(); 
      list.Import(_properties.Select(x => x.Name).ToArray()); 

      list.sEcho = (int)_tableParams[ECHO]; 

      list.iTotalRecords = _queriable.Count(); 

      ApplySort(); 

      int skip = 0, take = list.iTotalRecords; 
      if (_tableParams.ContainsKey(DISPLAY_START)) 
       skip = (int)_tableParams[DISPLAY_START]; 
      if (_tableParams.ContainsKey(DISPLAY_LENGTH)) 
       take = (int)_tableParams[DISPLAY_LENGTH]; 

      //tenho de segregar para mostrar o filtrado 
      list.aaData = _queriable.Where(ApplyGenericSearch) 
            .Where(IndividualPropertySearch) 
            .Skip(skip) 
            .Take(take) 
            .Select(SelectProperties) 
            .ToList(); 

      //tenho de segregar para mostrar o filtrado geral 
      list.iTotalDisplayRecords = _queriable.Where(ApplyGenericSearch) 
                .Where(IndividualPropertySearch) 
                .Select(SelectProperties) 
                .Count(); 
      return list; 
     } 
     private void ApplySort() 
     { 
      foreach (string key in _tableParams.Keys.Where(x => x.StartsWith(INDIVIDUAL_SORT_KEY_PREFIX))) 
      { 
       int sortcolumn = (int)_tableParams[key]; 
       if (sortcolumn < 0 || sortcolumn >= _properties.Length) 
        break; 

       string sortdir = _tableParams[INDIVIDUAL_SORT_DIRECTION_KEY_PREFIX + key.Replace(INDIVIDUAL_SORT_KEY_PREFIX, string.Empty)].ToString(); 

       var paramExpr = Expression.Parameter(typeof(T), "val"); 
       var propertyExpr = Expression.Lambda<Func<T, object>>(Expression.Convert(Expression.Property(paramExpr, _properties[sortcolumn]), typeof(object)), paramExpr); 


       if (string.IsNullOrEmpty(sortdir) || sortdir.Equals(ASCENDING_SORT, StringComparison.OrdinalIgnoreCase)) 
        _queriable = _queriable.OrderBy(propertyExpr); 
       else 
        _queriable = _queriable.OrderByDescending(propertyExpr); 
      } 
     } 

     private Expression<Func<T, List<string>>> SelectProperties 
     { 
      get 
      { 
       return value => _properties.Select 
              (
               prop => (prop.GetValue(value, new object[0]) ?? string.Empty).ToString() 
              ) 
              .ToList(); 
      } 
     } 

     private Expression<Func<T, bool>> IndividualPropertySearch 
     { 
      get 
      { 
       var paramExpr = Expression.Parameter(typeof(T), "val"); 
       Expression whereExpr = Expression.Constant(true); // default is val => True 
       foreach (string key in _tableParams.Keys.Where(x => x.StartsWith(INDIVIDUAL_SEARCH_KEY_PREFIX))) 
       { 
        int property = -1; 

        if (!int.TryParse(key.Replace(INDIVIDUAL_SEARCH_KEY_PREFIX, string.Empty), out property) || property >= _properties.Length || string.IsNullOrEmpty(_tableParams[key].ToString())) 
         continue; // ignore if the option is invalid 

        string query = _tableParams[key].ToString().ToLower(); 

        var toStringCall = Expression.Call(
             Expression.Call(
              Expression.Property(paramExpr, _properties[property]), "ToString", new Type[0]), 
                   typeof(string).GetMethod("ToLower", new Type[0])); 

        whereExpr = Expression.And(whereExpr, 
               Expression.Call(toStringCall, 
                   typeof(string).GetMethod("Contains", BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.IgnoreCase), 
                   Expression.Constant(query))); 

       } 
       return Expression.Lambda<Func<T, bool>>(whereExpr, paramExpr); 
      } 
     } 

     private Expression<Func<T, bool>> ApplyGenericSearch 
     { 
      get 
      { 
       if (!_tableParams.ContainsKey(SEARCH) || _properties.Length == 0) 
        return x => true; 

       string search = _tableParams[SEARCH].ToString(); 

       if (String.IsNullOrEmpty(search)) 
        return x => true; 

       var searchExpression = Expression.Constant(search.ToLower()); 
       var paramExpression = Expression.Parameter(typeof(T), "val"); 

       var propertyQuery = (from property in _properties 
             let tostringcall = Expression.Call(
                  Expression.Call(
                   Expression.Property(paramExpression, property), "ToString", new Type[0]), 
                   typeof(string).GetMethod("ToLower", new Type[0])) 
             select Expression.Call(tostringcall, typeof(string).GetMethod("Contains"), searchExpression)).ToArray(); 

       Expression compoundExpression = propertyQuery[0]; 

       for (int i = 1; i < propertyQuery.Length; i++) 
        compoundExpression = Expression.Or(compoundExpression, propertyQuery[i]); 

       return Expression.Lambda<Func<T, bool>>(compoundExpression, paramExpression); 
      } 
     } 

    } 

} 

我希望從來就幫助了您的問題!

0

你嘗試DataTable的插件它具有以下功能:顯示記錄按我們的要求.. 看到這個link

應用DataTable的插件爲網格要顯示的數據,你可以通過改變aLengthMenuiDisplayLength屬性更改此選項根據您的要求..這是建在功能

$(document).ready(function() { 
    $('#example').dataTable({ 
     "aLengthMenu": [[10, 20, 30, -1], [10, 20, 30, "All"]],// set as per your requirement 
     "iDisplayLength": 10 // dont forget to change as per alengthmenu 


    }); 
}); 
1

但是,我們必須添加一個list(可以是任何類型的列表)來datasource當我們使用DataGrid控制。

我們想要做的只是限制此list中的項目數,然後使用DataBind()綁定您的數據。

To limit number of data

var firstFiveItems = myList.Take(5); 

var secondFiveItems = myList.Skip(5).Take(5);