[c#] how to bind datatable to datagridview in c#

I need to bind my DataTable to my DataGridView. i do this:

        DTable = new DataTable();
        SBind = new BindingSource();
        //ServersTable - DataGridView
        for (int i = 0; i < ServersTable.ColumnCount; ++i)
        {
            DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
        }

        for (int i = 0; i < Apps.Count; ++i)
        {
            DataRow r = DTable.NewRow();
            r.BeginEdit();
            foreach (DataColumn c in DTable.Columns)
            {
                r[c.ColumnName] = //writing values
            }
            r.EndEdit();
            DTable.Rows.Add(r);
        }
        SBind.DataSource = DTable;
        ServersTable.DataSource = SBind;

But all i got is DataTable ADDS NEW columns to my DataGridView. I don't need this, i just need to write under existing columns.

This question is related to c# .net winforms data-binding datagridview

The answer is


foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

private void Form1_Load(object sender, EventArgs e)
    {
        DataTable StudentDataTable = new DataTable("Student");

        //perform this on the Load Event of the form
        private void AddColumns() 
        {
            StudentDataTable.Columns.Add("First_Int_Column", typeof(int));
            StudentDataTable.Columns.Add("Second_String_Column", typeof(String));

            this.dataGridViewDisplay.DataSource = StudentDataTable;
        }
    }

    //Save_Button_Event to save the form field to the table which is then bind to the TableGridView
    private void SaveForm()
        {
            StudentDataTable.Rows.Add(new object[] { textBoxFirst.Text, textBoxSecond.Text});

            dataGridViewDisplay.DataSource = StudentDataTable;
        }

for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by :

public DataTable  getAllUsers()
    {
        OracleConnection Connection = new OracleConnection(stringConnection);
        Connection.ConnectionString = stringConnection;
        Connection.Open();

        DataSet dataSet = new DataSet();

        OracleCommand cmd = new OracleCommand("semect * from Users");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Connection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet.Tables[0];
    }

step 2- set the return result to DataGridView :

public void setTableToDgv(DataGridView DGV, DataTable table)
    {
        DGV.DataSource = table;
    }

using example:

    setTableToDgv(dgv_client,getAllUsers());

Even better:

DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();

ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;

ServersTable.DataSource = SBind;
ServersTable.Refresh();

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.


On the DataGridView, set the DataPropertyName of the columns to your column names of your DataTable.


// I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.

 BindingSource SBind = new BindingSource();
 SBind.DataSource = dtSourceData;

 ADGView1.AutoGenerateColumns = true;  //must be "true" here
 ADGView1.Columns.Clear();
 ADGView1.DataSource = SBind;

 //set DGV's column names and headings from the Datatable properties
 for (int i = 0; i < ADGView1.Columns.Count; i++)
 {
       ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
       ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
 }
 ADGView1.Enabled = true;
 ADGView1.Refresh();

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to data-binding

Angular 2 Checkbox Two Way Data Binding Get user input from textarea Launch an event when checking a checkbox in Angular2 Angular 2 two way binding using ngModel is not working Binding ComboBox SelectedItem using MVVM Implement Validation for WPF TextBoxes Use StringFormat to add a string to a WPF XAML binding how to bind datatable to datagridview in c# How to format number of decimal places in wpf using style/template? AngularJS - Binding radio buttons to models with boolean values

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results