How to add a DataGridView to a Windows Form

To display data in a DataGridView on a Windows Form

  • Add a new form to the Win Form Application project
  • Drag a BindingSource from the Toolbox to the form
    Visual Studio Toolbox Data

 

  • The bindingSource object appears below the form
    Visual Studio DataGridview Binding DatSource insert

 

  • Rename the Binding Source
    • Select the bindingSource1 object below the form
    • Press F4 to display the Properties
    • Change the Name property to reflect the purpose of the object
      Visual Studio DataGridview Binding DatSource properties

 

  • Select the DataSource item in the Data section and click the Add Project Data Source… link
    Visual Studio DataGridview Binding DatSource properties select data source

The name is misleading. At this step we are not selecting the source of the data, we are selecting the object that describes the data row. The DataGridView will generate the columns based on the object we will select here.

  • To load the data from a class select Object as the Data Source Type and click Next
    Visual Studio DataGridview Binding Data Source properties choose data source type

 

  • Select the object that describes the data row you want to display
    Visual Studio DataGridview Binding Data Source properties select data object

 

  • Drag a DataGridView from the Toolbox to the form
    Visual Studio Toolbox Data data grid view

 

  • Select the small arrow at the upper right corner of the DataGridView to open the Tasks dialog
  • Click the down arrow next tot the Choose Data Source list
  • Select the Binding Data Source that you added to the form
    Visual Studio DataGridview select binding data source

 

  • Click the Edit Columns link to set the visibility of the columns
    Visual Studio DataGridview Edit Columns

 

  • To hide a column set the Visible attribute in the Appearance section to False
    Visual Studio DataGridview Column visibility
  • To load data into the DatGridView add the following code to the constructor of the form. In this example the GetUsers() method returns an array of UserView objects
    // Load the data into the DataGridView
    bindingSourceUsers.DataSource = _business.GetUsers();
  • To hide the row selector column on the left side of the data add the following to the constructor of the form. This option is not included in the property sheet of the DataGridView, so we have to set it in the code.
    dataGridView1.RowHeadersVisible = false;

Leave a comment

Your email address will not be published. Required fields are marked *