简体   繁体   中英

How to limit the number of rows in dataset

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

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";

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

string query = "SELECT TOP 10 FROM tblCountry";

您可以像这样进行查询,仅返回10行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM