Get Top N Rows using Datatable object.

Vishalneeraj-24503
Posted by Vishalneeraj-24503 under ADO.NET category on | Points: 40 | Views : 1451
Assume that we have a Datatable filled,then write below code as:-
public DataTable getTop(DataTable dt, int n)
{
DataTable outputTable = dt.Clone();
int i = 0;
for (i = 0; i < n; i++)
{
if (dt.Rows.Count == i)
return outputTable;

outputTable.ImportRow(dt.Rows[i]);
}
return outputTable;
}

protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (ViewState["Datatable"] != null)
{
DataTable dt = (DataTable)ViewState["Datatable"];
int topNRows = Convert.ToInt32(TextBox1.Text);
DataTable outputTable = getTop(dt, topNRows);
gv.DataSource = outputTable;
gv.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}

Just pass any value in getTop method,which will fetch first n record.

Comments or Responses

Login to post response