1

I am creating window application basic. As i have created datagrid with 2 columns but when i apply datasource to datagrid and that datasource has 10 columns then datagrid shows 2+10 columns. How to disply only 2 columns from 10 columns list coming from database.

Please don't use: 1) Don't delete columns from datagrid one by one. 2) Don't delete columns from list coming from database one by one.

Dot NET
  • 4,891
  • 13
  • 55
  • 98

5 Answers5

2

You will need to set AutoGenerateColumns to false on the datagrid and then bind the two columns that you created in the datagrid to the corresponding columns in the datasource.

Sir Rippov the Maple
  • 7,491
  • 5
  • 42
  • 52
  • I have code like this >>> dgContacts.DataSource = obj_BO_ContactDetailList;dgContacts.AutoGenerateColumns = false; –  Aug 23 '11 at 11:12
2

Set AutoGeneratedColumns property before assigning ItemsSource to datagridview.

Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70
Upendra Chaudhari
  • 6,473
  • 5
  • 25
  • 42
0

First check if AutoGenerateColumns property of DataGridView is false this will stop the generation of the columns.

I presume you want to map the data in 2 columns of your total 10 columns of the DataSource to the DataGridView columns, for that check if you have defined DataPropertyName for the existing 2 columns which should map to the respective columns of the datasource

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
0

Just Set AutoGeneratedColumns property to False, before set data source to data grid. Otherwise data grid will added columns itself.

DataGridView grid = new DataGridView();
grid.AutoGenerateColumns = false;
Sampath
  • 1,173
  • 18
  • 29
-1

You can do this to hide a specific column.

//Were 0 is the index of the column.
dataGridView.Columns[0].Visible = false;

Update :

Didn't see that last part of the question. You could create anonymous list of only the columns you want to show. This was you don't have to go though the hassel of setting up each column of your DataGridView

Example.

var smallList = listFromDb.Select(c=> new {c.Name, c.Age});
dataGridView.DataSource = smallList;
Jethro
  • 5,896
  • 3
  • 23
  • 24
  • @CodeBlend, are you asking me why I got downvoted or why I downvoted, cause I didn't. – Jethro Aug 23 '11 at 11:12
  • Because this approach isn't the best way to do it, your just hiding the problem, the fact your getting more data then you need. – Security Hound Aug 23 '11 at 11:14
  • Let me rephrase that - Comment if you downvote guys! – Paul C Aug 23 '11 at 11:14
  • I didn't down vote this, but probably as the question stated that the answer shouldn't be to remove columns one-by-one? It mentions deletes, but it most likely extends to hiding as well? – fatty Aug 23 '11 at 11:15
  • @Ramhoud, It all depends on the developer, what if he/she wanted to hide the first column that contained CodeId's? This is info the developer can use but info that the user does not need to see. – Jethro Aug 23 '11 at 11:16