简体   繁体   中英

How To Display Specific Row Of The DataSet in The GridView

I have Table "Data".

  ID |  Name  |  Params   |
 --------------------------
  1  |  a     |  233      |
  22 |  a     |  34       |
  123|  a     |  123      |
  839|  a     |  2344     |
 --------------------------

And I use the following SQL to retrieve the data from the Table:

"SELECT * FROM Data WHERE Name='" + Name + "'"
Adapter.Fill(Data);
DataList.Add(Data); 
Return Data;

Everything works if I want to display everything at once in the GridView, However, I'd like to be able to display only specific Rows of the DataSet.

Question: How would I be able to display specific Row of the DataSet given an Index?

The following example shows an error:

Gridview.DataSource = UserDataList.Tables[0].Rows[1];

Thank you in advance.

You can't do that because UserDataList.Tables[0].Rows[1] returns a single row but the datasource of gridview expects an IEnumerable or collection of data like rows. You can filter your datatable using LINQ like this:-

Gridview.DataSource = UserDataList.Tables[0].AsEnumerable()
                                  .Where((v, i) => i == 0).CopyToDataTable();

I have used the Where extension method. Here i is the index of rows in your table. You can fetch any row by providing the correct index. Also, one good thing is you can filter your table based on any column you wish.

Try this

ds means dataset here.

using index

ds.Tables[0].Rows[0][4].ToString();

using column name

ds.Tables[0].Rows[0]["columnname"].ToString()

First you convert your DataTable to DataView like

DataView dv = new DataView(dt);

Then apply filter query like

dv.RowFilter = "id=10";

And finally convert it back to table

DataTable newtbl = dv.ToTable();

This newtbl will contain filtered data.

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