开发者

how to display few records from a database in dataviewgrid control in c#?

suppose i am having a database table with 20 records and of that i want to display only 10 records in the dataviewgrid contr开发者_JAVA技巧ol, how can i achieve this?


You can write a query like this:

SELECT * FROM (
  SELECT TOP 10 * FROM (
    SELECT TOP 20 * FROM MyTable ORDER BY MyID ASC
  ) AS NewTbl ORDER BY MyID DESC
) AS NewTbl2 ORDER BY MyID  ASC

This selects records 11-20. If you want to select records 6-15 just change 20 to 15.
20 is the "last record to select" and 10 is the number of records before and up to 20.

Edit (After your comment about having all rows in a DataSet):

var newDS = new DataSet();
newDS.Tables.Add(oldDSWithAllRows.Tables["YourTableName"].Clone());

foreach (DataRow myDataRow in oldDSWithAllRows.Tables["YourTableName"].Rows)
{
  if (/* Your criteria */)
  {
    newDS.Tables["YourTableName"].ImportRow(myDataRow);
  }
}

myDataGridView.DataSource = newDS;


Select only the 10 records you want.

In SQL use the TOP clause:

SELECT TOP 10 * FROM myTable


use DataTable.Select

usage:

dataSet1.Tables[0].Select("Id>5");

or, better, DataView with a RowFilter, example here

you can set tha DataGridView.DataSource to this DataView


If you're using the latest version of C# you could filter your source with LINQ:

// change Skip to 10 to page through
var filtered = mydatasource.Skip(0).Take(10); 

This assumes you've returned your SQL data as an IEnumerable<T>


Suppose we have the following table

DataTable dt = new DataTable();
int counter = 1;
dt.Columns.Add("ID");
dt.Columns.Add("Name");
for (int i = 1; i <= 20; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = i;
dr["Name"] = string.Format("Name{0}", i);
dt.Rows.Add(dr);
}

You can bind the grid this way:

this.GridView1.DataSource = dt.AsEnumerable().Take(10);
this.GridView1.DataBind();

but: this can work if you did the following: -Add two template fields to the gridview -Add the following function to the code behind page:

protected object GetColumnValue(object Row,string columnName)
        {
            DataRow dr = Row as DataRow;
            return dr[columnName];
        }

Edit the DataBindings of the fields of the gridview to bind this way:

GetColumnValue(Container.DataItem,"ID") //for the first Field
GetColumnValue(Container.DataItem,"Name") //for the second field
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜