2016-08-19 54 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);