Darshn
Darshn

Reputation: 1601

Add few records to gridview from DataTable

I have been working on asp.net/C# project. I could bind the DataTable to gridview. But i have a situation where i don't want to bind all the records in DataTable. is there any method to bind only few records to gridview? any Alternatives to GridView.DataBind()?

Thank you

Upvotes: 0

Views: 1134

Answers (3)

Jignesh Khokhariya
Jignesh Khokhariya

Reputation: 150

try this,

using datatable select query you can achieve this, for example,

DataTable dt=yourdata;
DataRow[] dr=dt.Select("columnname='Maths'");

foreach (DataRow row in dr) {
   dt.ImportRow(row);
}
GridView1.DataSource=dt;
GridView1.DataBind();

where Maths = your search criteria.

Upvotes: 1

Sarathi Jayapal
Sarathi Jayapal

Reputation: 300

Use DataView for the DataTable, So that you can able to filter records and assign the dataview to Grid.

for example:

DataView dv = new DataView(DataTable, "Column1=Value", "Column2", DataViewRowState.CurrentRows);

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

You can add the rows manually, i.e. without using a data source.

var newRowIndex = dataGridView1.Rows.Add(firstValue, secondValue, thirdValue);

You might use it like this:

foreach (System.Data.DataRow row in myDataTable.Rows)
{
    if(meets my criteria...)
    {
        dataGridView1.Rows.Add(row["Column1"], row["Column2"], row["Column3"]);
    }
}

In fact, this may be a better solution as it allows you to sort columns easily in the UI whereas binding to a data source does not allow that.

Upvotes: 0

Related Questions