Home » VB.Net

Hiding Columns in a DataGridView using BindingSource


I bind a dataTable to a data grid view by using a binding Source as follows:

adapterEmployees =


newSqlDataAdapter("select * from Employee", con);










I'd like to hide some of the columns. Retrieving the specific wanted-to-be-shown columns, won't be good enough for my case, as I need the dataSource to know all the columns.


Thanks in advance



2 Answers Found


Answer 1


The columns  in a DataGridView have a visible property.  You could iterate over the columns of the dgv and only set certain columns visible. Ex.

foreach(DataGridViewColumn column in dgvEmployees.Columns)
    column.Visible = true;
    column.Visible = false;


Answer 2

Turn off auto-generate columns  and define them yourself. Then you can just define the columns you need, regardless of which columns are in the datasource.

Just be sure to set the DataPropertyName for each column to the field in the bound dataset that you want to bind  to.

Hope this helps.


i have a datagridview that is bind to a bindingsource, the bindingsource.datasource is set a typeof() when the form initialize and then i change the datasource to my datatable at the form load event. at design time, i set the id columns and couple of other columns visibility to false, but when i run the program, the id columns visiblity changed to true when i change the bindingsource.datasource to my datatable, but the other columns didnt change.  this is very strange because only the id columns visibility changes. for now i just set the visibility to false again after changing the datasource property. but why is this happening?

I am trying to solve this already couple of days without any success...

I have a datagridview, I set its datasource to dataview, it works fine.

But after this I want to hide some columns during runtime, I can hide without any problems any column EXCEPT 1st one.

As a test I made a method with one line of code "dgMaterial.Columns[0].Visible = false;". I put a button on my form beside datagridview dgMaterial and when I click on this button it calls this method and it happens that the 1st column is HIDDEN!

So I can hide 1st column but not during runtime, I am almost sure that it is some detail but I really can not find it out.

I was also trying to change CurrentCell because I found out somewhere that you can not hide column with CurrentCell but I was not succesfull. Reason is probably because dataview, which is datasource for my datagridview, is empty (without any rows)

Thank you in advance for any advice.





I've posted this question on a few other forums and I'm getting no response at all so I think maybe it's i nthe wrong forum so I'll try here. I just need maybe a nudge in the right direction. I wanted to have a datagridview that gets it's data from two tables off my SQL2005 server. I have a table lineitems and a table vendors. The linelitems table has a field: VendorID which is a foriegn key for the vendor table. I can't ever seem to get the data source working whereI pull it over and it auto creates it so I wanted to do this in code. I've gotten the DGV to come up exactly the way I want it except I can't save and I can only edit two columns. One is Replaceddescription and the other is depreciation. So any ideas on where I should go from here?

Thank you so much for taking the time to read this and help me out.

Code Snippet

PrivateSub LoadLineItemData()



Me.ToolStripStatusLabel1.Text = "Claim Number " & SelectedClaimNumber

Me.ToolStripStatusLabel3.Text = "Notes"

Dim LineItems = From LI In db.ClaimLineItems _

Where LI.ClaimNumber = SelectedClaimNumber _

Select LI.LineItemID, LI.Sort, LI.Qty, LI.LostItemDescription, LI.Retail, LI.Price, LI.Cost, LI.VendorID, LI.Replaceable

Dim Vendor = From VN In db.Vendors _

Select VN.VendorID, VN.VendorName Distinct

With BindingSourceLineItems

.DataSource = LineItems


BindingVendors.DataSource = Vendor

Dim LineItemIDColumn AsNew DataGridViewTextBoxColumn

With LineItemIDColumn

.DataPropertyName = "LineItemID"

.HeaderText = "LineItemID"


Dim SortColumn AsNew DataGridViewTextBoxColumn

With SortColumn

.DataPropertyName = "Sort"

.HeaderText = "Sort"

.ReadOnly = False


Dim QtyColumn AsNew DataGridViewTextBoxColumn

With QtyColumn

.DataPropertyName = "Qty"

.HeaderText = "Qty"


Dim ReplacedItemDescriptionColumn AsNew DataGridViewTextBoxColumn

With ReplacedItemDescriptionColumn

.DataPropertyName = "ReplacedItemDescription"

.HeaderText = "ReplacedItemDescription"


Dim RetailColumn AsNew DataGridViewTextBoxColumn

With RetailColumn

.DataPropertyName = "Retail"

.HeaderText = "Retail"


Dim PriceColumn AsNew DataGridViewTextBoxColumn

With PriceColumn

.DataPropertyName = "Price"

.HeaderText = "Price"


Dim CostColumn AsNew DataGridViewTextBoxColumn

With CostColumn

.DataPropertyName = "Cost"

.HeaderText = "Cost"


Dim DepreciationColumn AsNew DataGridViewTextBoxColumn

With DepreciationColumn

.DataPropertyName = "Depreciation"

.HeaderText = "Depreciation"


Dim LIDComboBox AsNew DataGridViewComboBoxColumn

With LIDComboBox

.Name = "Vendors"

.DataPropertyName = "VendorID"

.DataSource = BindingVendors

.DisplayMember = "VendorName"

.ValueMember = "VendorID"


Dim ReplaceableColumn AsNew DataGridViewCheckBoxColumn

With ReplaceableColumn

.DataPropertyName = "Replaceable"

.HeaderText = "Replace?"


With DataGridView1

.AutoGenerateColumns = False

.DataSource = BindingSourceLineItems

.AlternatingRowsDefaultCellStyle.BackColor = Color.Violet











.AllowUserToAddRows = True


DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically

DataGridView1.EditMode = DataGridViewEditMode.EditOnKeystroke

Dim ClaimNotes = From CN In db.ClaimNotes _

Where CN.ClaimNumber = SelectedClaimNumber _

Select CN

With DataGridView2

.DataSource = ClaimNotes

.AlternatingRowsDefaultCellStyle.BackColor = Color.LightSteelBlue


Catch ex As Exception





Can someone please help me with this issue.

My BindingSource is populated via ((IList the bindingsource is updated from changes made by the user in the datagridview but the ObjectContext is not refreshed/updated from the binding source.  So a call to BindContext.SaveChanges() does nothing to the DB.

aspnetAppThemeUserSettingBindingSourceRegisteredApps.DataSource = ((


This "results" is the return of



<AspnetAppThemeUserSetting> GetMyRegisteredApplicationsList()


//List<AspnetAppThemeUserSetting> results;

BindContext =




results = from i in BindContext.AspnetAppThemeUserSettings.Include("AspnetApplicationThemeGroup")












where i.AspnetUser.UserName == "3001497"



where i.AspnetApplication.AspnetMemberships.Where(oo => oo.IsApproved == 1 && oo.IsLockedOut == 0).Count() > 0



//Execute(System.Data.Objects.MergeOption.AppendOnly);//Objects.Mer.Merge//orderby i.AspnetApplication.ApplicationName


select i;



return results;

When the bindingsource gets its data from my BindContext object which does not have a using statement and the BindContext is declared form wide.  The datagridview is rendered with all of the row detail.  I then make changes to the datagrid and these changes are nicely reflected in my bindingsource however when i make a call to BindContext.SaveChanges() the BindContext makes no updates to the DB.  When i look at the BindContext in debug i can see that the old values are still there no changes have been made to the bind context.

Please help.




I've a DGV on my form application.

The DGV.Datasource is set to Me.MyBindingSource. I this the right way?

I'm using the Filter Method of the BindingSource to show only the rows I want of my DataSet.

When I delete some rows at run time in code (...rows.delete) and even after I update the Table, using the TableAdapter.Update method, not always this changes are reflected on the DGV, why is this happening?

Must I do some kind of refresh to the DataSet/BindingSource? maybe a new Fill to the DataSet? I not sure how to solve this...

Help please.



I find that in order to automatically obtain the correct value of an ID field of a table bound to a datagridview I have to set the "AlowUserToAddRows" property to False and then include the following code in a button:

 If MsgBox("Create a new model?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
 Dim aRow As DataRow = dtModelBudget.NewRow()
 UserModelsDataGridView.Refresh() 'Adds a row to the DataGridView
 UserModelsDataGridView.Rows(UserModelsDataGridView.Rows.Count - 1).Selected = True 'Selects last row
 End If

I handle getting the updated ID values with the following:

'Added in Load method of screenAddHandler taModelBudget.RowUpdated, AddressOf taModelBudget_RowUpdated

'Added to screen codePrivateSub taModelBudget_RowUpdated(ByVal sender AsObject, ByVal e As System.Data.OleDb.OleDbRowUpdatedEventArgs) Handles taModelBudget.RowUpdated
  'isLoaded is set to true at the end of the Load methodIf isLoaded ThenIf e.Status = UpdateStatus.ContinueAndAlso e.StatementType = StatementType.Insert ThenDim sql AsString = "SELECT @@IDENTITY"Dim cmd AsNew OleDbCommand(sql, e.Command.Connection)
    e.Row("ModelID") = cmd.ExecuteScalar()

This works great when the datagridview is bound to the datatable directly.  Things get more complicated when I bind the datagridview to a bindingsource that is in turn bound to the datatable.  While more complicated, this allows me to use a bindingnavigator and also have text boxes bound to the table as well as the datagridview.  The problem comes when I try to add a datarow to the datatable and get an error.  I suspect I should be adding a row through the AddNew or Add method of the bindingsource, but when I attempt to add a datarow I get the error that I am not adding the correct data type to the list contained in the bindingsource.  Any suggestions on how to solve this?



Hi all.

I think that I have a very common problem. A linq2Entities source, a winForm BindingSource bound to it and a DataGridView bound to the BindingSource. The problem is: the automatic sorting of datagridview doen'st work.

but the solution from Diego doesn't work in my case.

this is my scenario:

I get some data using this function (that is waht I suppose the post suggests

public IList Get()
       var result = from vendita in context.VenditaSet
                         join cliente in context.ClienteSet on                   vendita.CodiceCliente equals cliente.Codice
                         join articolo in context.ArticoloSet on vendita.CodiceArticolo equals articolo.Codice
                         select vendita;
        return ((IListSource)result).GetList();

And then I bind this data to a bindingsource and the binding source to a datagridview.

But the automatic sorting mode of the datagridview doesn't work :-(

Thanks all a lot


I would like to bind the DataGridView "myDataGridView" on Form1 to the ListObject "Adressliste" in the EXCEL Worksheet "Tabelle1".


I tried the following Code

private void Form1_Load(object sender, EventArgs e)
            BindingSource source = new BindingSource(Globals.Tabelle1.Adressliste,"");
            this.myDataGridView.DataSource = source;


and there is some connection, but myDataGridView shows Columns like Application, Creator, Parent and so on.

I do not seem to fully understand binding. Can someone please help me?

I'm in the process of writing an application encountered a problem and I can not find the information that would help me solve my problem.

Code aplication:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

using myConnectionSQL;

namespace WindowsFormsApplication1
    public partial class FormDealer : Form
        public FormDealer()

        private SqlConnection connection = null;
        private SqlDataAdapter adapter = null;
        private DataSet ds = null;
        private SqlCommand selCommand = null;
        private SqlCommand insCommand = null;
        private SqlCommand updCommand = null;
        private SqlCommand delCommand = null;

        private string id_dealer = string.Empty;

        private void FormDealer_Load(object sender, EventArgs e)
            connection = new SqlConnection(mySQL.connectionString);
            selCommand = new SqlCommand("SELECT * FROM Dealer", connection);
            insCommand = new SqlCommand("INSERT INTO Dealer (name_dealer, phone_dealer, mail_dealer) VALUES(@Name, @Phone, @Mail)", connection);
            updCommand = new SqlCommand("UPDATE Dealer SET name_dealer=@Name, phone_dealer=@Phone, mail=@Mail WHERE id_dealer=@DealerID", connection);
            delCommand = new SqlCommand("DELETE FROM Dealer WHERE id_dealer=@DealerID", connection);
            adapter = new SqlDataAdapter();
            adapter.SelectCommand = selCommand;

        private void Fill()
            ds = new DataSet("Informacje o sprzedawcach");
            bindSrc.DataSource = ds;
            bindSrc.DataMember = ds.Tables[0].TableName;
            dataGrid.DataSource = bindSrc;

        private void btnAdd_Click(object sender, EventArgs e)
            insCommand.Parameters.AddWithValue("@Name", tbName.Text.Trim());
            insCommand.Parameters.AddWithValue("@Phone", tbPhone.Text.Trim());
            insCommand.Parameters.AddWithValue("@Mail", tbMail.Text.Trim());

            catch (Exception ex)


        private void bindSrc_CurrentChanged(object sender, EventArgs e)
            DataRowView row = (DataRowView)(bindSrc.Current); // this is error
            id_dealer = row.Row[0].ToString().Trim();
            string name_dealer = row.Row[1].ToString().Trim();
            string phone_dealer = row.Row[2].ToString().Trim();
            string mail_dealer = row.Row[3].ToString().Trim();

            tbName.Text = name_dealer;
            tbPhone.Text = phone_dealer;
            tbMail.Text = mail_dealer;

I'm working on an application which interact with access database, in my form, i have a simple dataGridView which bound to bindingSource.
i've invisible first column of my dataGridView.
my problem is that when i change the bindingSource.DataSource property to another dataSource, my dataGridView column become visible!
i don't know why this issue occures.

(Also, i have similar problem in another place when i call myDataSet.AcceptChanges(), after this my invisible dataGridViewRows become visible!)

can anybody help me where is my problem and how to solve it ?
thanks in advance

I have WinForm client developed using .NET 3.5 SP1/EF/VS2008

I am using Winforms Binding source and binding Array of EF entities. DataGridView is in turn bound to binding source.

In EF Entity (Ex: Employee), I have a property "OfficeID" in database table -> Which mapped to "Office" and "OfficeReference" in "Employee" entity.

I do have valid Office ID assigned to each Employee and I verified that: OfficeReference.EntityKey is valid -> after I got the Array Of Entities in client.

WinForm DataGridView/BindingSource Binding Problem?

   - In DataGridView, I want Office column to show up Office name or Office ID
   - But when I bind data, I see nothing MAINLY for all FK columns/properties in the Entity (Even through their references are correct)

Please let me know what I am missing OR if this is some known issue with WinForms binding with EF entities.


I have 2 datagridviews on different tabs of a tabcontrol.

The user can input names into datagridview1 column1. I want these names to automatically appear in datagridview2 column1, in such a way that when rows in datagridview1 are added and removed the same rows are added and removed in datagridview2. I also want the column sort function to effect datagridview2.



I dragged a DataTable with a two-column primary key onto my Form in Details view (not DataGrid ) and added a 'Query' Button .

The QueryBtn_Click() should query the database with the values in the textboxes corresponding to the primary key, then populate the remaining fields for that record. If the record is not found, do nothing.

The BindingSource.Find() and BindingSource.IndexOf() both seem to only search on one field.

How do I achieve the above behavior?

Note: C# answers acceptable, but VB.NET code is preferred.



I was wondering if anyone can help me.

I have a BindingSource in my Windows Form and this is linked to a table which has two columns one is 'id' and the other is 'PO' there is only one row which shows in there as i have filtered it that way. So what i am trying to do is retrieve the current value under the 'PO' column.

I have written this code in vb before and it works perfectly. I need to know what the C# code is.

The VB code was :   label1.text = me.BindingSource1.current("PO").ToString()

I have tried the following codes for C#

label1.text = this.BindingSource1.current("PO").ToString();


label1.text = this.BindingSource1.current("PO".ToString().ToString());

it keeps throwing up the following error : Non-Invocable member 'systems.windows.forms.bindingsource.current' cannot be used like a method.

Please can someone help.





Hai friends,

I've a datagridview using C# .net which has been get data fields from MySql and displays like


FirstName    |    LastName   |    ID   


Kelvin          |    David         |   001

Maria           |    John           |   002

Joe              |    Martin         |   003


This above example shows the datas with 3 fields which is in MySql dataBase Table name "Details"

I want to display it in my datagridview as like give below




Kelvin  David  001

Maria  John    002

Joe  Martin 003


This is showing in a single field. And it should be with the same table "Details"

Waiting for Answer...

Thank you....


I am new to using VB Express (2008 and 2010). I have an .mdb database with 4 tables. I am able to show a detail form with a couple of comboboxes linked to their related tables so as to show Name rather than the numeric foreign key.

Now I am trying to link the same foreign-key columns in a DGV to show Name and not the key, but can't figure out how to achieve that?

The answer may already be in this forum, but I can't find it!!

Can somebody help me, please?

Cheers, Bill



I have the following code to add a new column into the datagridview but how to default value to this column?

I do not want to use for loop to loop through each row and get the column updated, is there any other way?

I want to default them to 'N' and i will have the code to change it to 'Y' subsequently based on conditions.


        dgDataConfiguration.Columns.Add("Update", "Update")


Many thanks.


How can i hide columns and rows in SharePoint newform.aspx list based on salected item in dropdown column. Please provide example.





I want to be able to hide some of the columns of this report.  For example , I don't want to see the % of State Total for Total column, and I don't want to see the % of Location Total for the other column groups.  Can this be done?  Any help would be appreciated.  Thanks J

I am using Visual Studio 2005

 Total Anaheim CAArlington VAAtlanta GA
Count% of State Total% Of Location TotalCount% of State Total% Of Location TotalCount% of State Total% Of Location TotalCount% of State Total% Of Location TotalCount% of State Total% Of Location Total
USA 3100.00%0.02% 0.00%0.00% 0.00%0.00% 0.00%0.00% 0.00%0.00%
 AB2100.00%0.01% 0.00%0.00% 0.00%0.00% 0.00%0.00% 0.00%0.00%
 AE8100.00%0.04% 0.00%0.00% 0.00%0.00%337.50%0.10%112.50%0.07%
 AK32100.00%0.17% 0.00%0.00% 0.00%0.00%39.38%0.10%13.13%0.07%
 AL161100.00%0.85% 0.00%0.00% 0.00%0.00%1710.56%0.54%8452.17%6.11%
 AP3100.00%0.02% 0.00%0.00% 0.00%0.00% 0.00%0.00%133.33%0.07%


Infopath 2007
browser based form
Full Trust

Example: I have a repeating table (FruitChoice) that has multiple columns.

Both drop down list point to sharepoint list data sources.

Choose your tree ft. drop down list – 6Ft
Choose your Department drop down list - 103

This repeating table is conditional on the drop down values. This works great.

Trees     Fruit       Cost   Date Ordered    Date Delivery Department
6Ft        Peaches                                                        103
3Ft        Apples                                                          102
3Ft        Peaches                                                        102
6Ft        Apples                                                          103
3ft        Plums and so on ....

Whatever is showing grab the values above and put them into these text boxes:

Text box Peaches - Peaches
Text box Apples -   Apples
Text box Plums  - 
Text box Tomato –

Ok, I have my values. Now that I have my values above I need to use those value in the next repeating table (Fruit and Department).

Based on another Sharepoint List Repeating table.

My condition for the Repeating table is Department, from the dropdown above, and the text box values. Hide if they do not match.

If peaches and apples are in the text box, along with the Department, then I would like the repeating table to hide the rows of the other fruits.

I can only get the first value to work, example Peaches. If I have either one in the conditional formating nothing show. I tried OR and also separate conditions. I know this works, because I have seen it, but cannot find the site where I seen it at.

Any support or answers would be appreciated.


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure