The structure of DataGrid and DataTable is identical. When trying to write this:

DataGridVeiw.DataSource = DataTable; //Псевдокод 

In the DatagridView on the right, DataTable columns are pasted.

enter image description here

Do not advise to fill in a cycle. Explain the reason? How to correctly and quickly fill in the Datagrid from DataTable?

  • columns added from the code and columns from the DataTable are displayed in the DataGridView. Set DataGridView.AutoGenerateColumns = false; or do not create columns in code - Stack
  • Creating columns in the code, I set the formatting and certain access rights for them. DataGridView.AutoGenerateColumns = false (The columns simply will not be created and the result will be an empty grid with the columns I created). - Alexander Puzanov
  • "Columns are simply not created" - try to indicate in columns in the code which columns in the DataTable should be attached. see DataGridViewColumn.DataPropertyName - Stack
  • I'll try - write off - Alexander Puzanov

2 answers 2

 // #r "System.Windows.Forms" using System.Windows.Forms; using System.Data; var t = new DataTable(); t.Columns.Add("c1", typeof(int)); t.Rows.Add(1); t.Rows.Add(2); var f = new Form(); var g = new DataGridView() { Parent = f, Dock = DockStyle.Fill, AutoGenerateColumns = false }; g.Columns.Add( new DataGridViewTextBoxColumn() { DataPropertyName = "c1", // привязка столбца грида к DataColumn HeaderText = "С 1" }); g.DataSource = t; f.ShowDialog(); 

    Your "pseudocode" is basically correct.

    Just when filling in the DataTable, let's give the columns normal names (if you fill in from the database, add AS 'ColumnName' to the query ...) for example:

     SELECT somename AS 'Имя' FROM sometable; 

    Then:

      using (MySqlConnection con = new MySqlConnection()) { con.ConnectionString = MSB.ConnectionString; MySqlCommand com = new MySqlCommand(Query, con); DataTable DT = new DataTable(); try { MySqlDataAdapter adr = new MySqlDataAdapter(Query, con); adr.SelectCommand.CommandType = CommandType.Text; adr.Fill(DT); return DT; } catch (Exception e) { Error = e.Message; return null; } } 

    and then assign the DataTable as the source DataGridVeiw

     DataGridVeiw.DataSource = DataTable; DataGridVeiw.Update(); 

    At the same time in the DataGridVeiw column do not need to create.

    • Thanks for the detailed answer. This is all I know. But certain columns are available for reading, others for writing, different formatting for all, etc. Please read my question again. - Alexander Puzanov
    • So what's the problem? Assigned the data source, then set the required behavior to the columns ... - SYL
    • There are columns that are not filled from the data source. Please do not impose your decision. I need to create columns, then some of them are filled with data from the source. - Alexander Puzanov
    • As an option to create the necessary columns in the DataTable before binding - SYL