Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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>();

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";
string query = "SELECT TOP 10 FROM tblCountry";

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top