Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind specific Columns of a datatable to a DataGridView?

My DataTable has three columns fetched from a database, while I need to bind only two columns of it to a DataGridView. Can you please help me with it?

like image 705
Sangeetha Avatar asked Feb 05 '11 14:02

Sangeetha


4 Answers

This may be useful

DataSet ds = new DataSet(); <-- Get data from Database here
DataTable dt = ds.Tables[0];
DataView view = new DataView(dt);
DataTable resultTable = view.ToTable(false, "Column1", 
"Column2","Column3","Column4","Column5","Column6");
dataGridView.DataSource = resultTable ;
like image 75
Eranda Madusanka Avatar answered Sep 18 '22 21:09

Eranda Madusanka


Create the columns for the DataGridView yourself. Try something like this.

DataGridView dataGridView1 = new DataGridView();
BindingSource bindingSource1 = new BindingSource();

dataGridView1.ColumnCount = 2;

dataGridView1.Columns[0].Name = "Field1";
dataGridView1.Columns[0].DataPropertyName = "Field1";
dataGridView1.Columns[1].Name = "Field2";
dataGridView1.Columns[1].DataPropertyName = "Field2";

bindingSource1.DataSource = GetDataTable();
dataGridView1.DataSource = bindingSource1;
like image 29
JoeyRobichaud Avatar answered Sep 19 '22 22:09

JoeyRobichaud


Add the column as answered above, and do not forget to set:

dataGridView1.AutoGenerateColumns = false;
like image 21
Nomi Ali Avatar answered Sep 19 '22 22:09

Nomi Ali


This was asked a while ago, so you probably won't need this answer... Hopefully others will find it useful.

I had to do something similar, and I found that the simplest solution was to create a temporary copy of the table (in which your data is stored) and then to simply remove the column in question. For example:

DataTable temp = YourDataTable;
temp.Columns.Remove(temp.Columns[2]) // Will remove the third column for example
YourDataTable.DataSource = temp;
YourDataTable.DataBind();

I think this should do the trick!

Cheers!

like image 3
Adrian Avatar answered Sep 21 '22 22:09

Adrian