简体   繁体   中英

Extracting Specific Columns from a DataTable

I have some code in my C# application which extracts data from a SQL database.

This DataTable is used in various places throughout my application, and is displayed in multiple DataGridViews .

However, I want to show only some of the columns in the Datatable , not all of them.

Also the columns I want to display are different in each of the DataGridViews .

eg

  • Show Columns 1-3 in DataGridView1
  • Show Columns 4-6 in DataGridView2
  • Show Columns 7-12 in DataGridView3

etc

I could of course just write different code to extract the required fields from SQL for each of the DataGridViews , but this doesn't seem like a very concise solution.

It would be better (I think) if I could use the one DataTable extracted from SQL, and apply multiple filters to it in the application for displaying different Columns in each of the DataGridViews .

I looked at using DataView but whilst this has a Sort method, it doesn't seem to have a Filter method

eg

DataTable table = GetDateFromSql();
DataView view = new DataView(table);
view.Sort = "FieldName";

Ideally I'd like to be able to do something like -

view.Filter = "SELECT cola, colB, colC";
myDataGridView.DataSource = view;

I know there is a RowFilter method, but in effect, its the Columns I want to filter.

How can this be done?

You can do something like this:

Similar Question: Showing only selected column in dataview

DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "FirstColumn", "SecondColumn", "ThirdColumn");

You can set DataGridViewColumn property visible to false, if You dont care about the data in that column. In asp.net web forms You can get the column by its name.

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