3

Code to refer

 [WebMethod]

 public static string GetData()
 {
      string query = "SELECT * FROM tblCountry";
      SqlCommand cmd = new SqlCommand(query);
      return GetData(cmd).GetXml();
 }
 private static DataSet GetData(SqlCommand cmd)
 {
      string strConnString = @"Data Source=.\sqlExpress;Initial Catalog=dbTest;Integrated  Security=SSPI; pooling=false";
      using (SqlConnection con = new SqlConnection(strConnString))
      {
          using (SqlDataAdapter sda = new SqlDataAdapter())
          {
             cmd.Connection = con;
             sda.SelectCommand = cmd;
             using (DataSet ds = new DataSet())
             {
                sda.Fill(ds);
                return ds;
             }
          }
      }
 } 

See more at: Link

The query returns 20 rows and i need to show ten rows alone. Without any alteration in query is there any possibility to limit the data in dataset.Suggest some ideas

Alex Wiese
  • 8,142
  • 6
  • 42
  • 71
Angelina
  • 85
  • 1
  • 2
  • 7

4 Answers4

5

You can try this

var rows = ds.Tables[0].AsEnumerable().Take(10);

Now you can also convert these rows into a datatable like this

DataTable limitedTable = rows.CopyToDataTable<DataRow>();
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • Was about to post this answer. Remember to add reference to your project for System.Data.DataSetExtensions or this won't work. – Esko Jan 31 '14 at 10:02
1

You can use an overload of Fill that takes the start and end record index.

var ds = new DataSet; //using means the DataSet will go out of scope so you can't return it!
sda.Fill(1, 10, ds.Tables.Add("MyTable"));
return ds; //it now contains a table called "MyTable".

You can find more details here

But like most commenters here, I'd be much more in favour of modifying the query if at all possible

Stephen Byrne
  • 7,400
  • 1
  • 31
  • 51
0

How strict is your requirement to not alter the query? Can you prepend some text to the query?

If so, you can use SET ROWCOUNT.

Example:

string query = "SET ROWCOUNT 10;"
query += "SELECT * FROM tblCountry";
mohlman3
  • 311
  • 3
  • 7
-2
string query = "SELECT TOP 10 FROM tblCountry";

You can make a query like this, to return only 10 rows.

Muneeb Zulfiqar
  • 1,003
  • 2
  • 13
  • 31