Pratik Gandhi
Pratik Gandhi

Reputation: 247

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 control, how can i achieve this?

Upvotes: 2

Views: 1721

Answers (5)

Sani Huttunen
Sani Huttunen

Reputation: 24375

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;

Upvotes: 1

Mostafa Elmoghazi
Mostafa Elmoghazi

Reputation: 2154

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

Upvotes: 0

Chris S
Chris S

Reputation: 65426

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>

Upvotes: 0

Catalin DICU
Catalin DICU

Reputation: 4638

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

Upvotes: 0

Oded
Oded

Reputation: 498914

Select only the 10 records you want.

In SQL use the TOP clause:

SELECT TOP 10 * FROM myTable

Upvotes: 1

Related Questions