Fill DataGrid with DataTable

0

The current situation is that I have this

dataGrid1.ItemsSource = dt.DefaultView;
            datagridajuste();

The problem is that when I fill in my "datagrid" (no datagridview), this generates empty tables at the beginning and at the end. So what I was looking for was to put the columns with the datagrid.Columns.add () but I never get it to work with the dt.

Also I would like to know if anyone knows how I can do so that once the datagrid is full and with a size set from the beginning, the contents of the datagrid are adjusted to the size of the datagrid (I have tried with the

dataGrid.AutoResizeColumns(DataGridViewAutoSizeColumnsMo‌​de.Fill) 

but directly I do not recognize the functions).

I have searched for datagrid information but everything I find is too outdated or does not specify the functions that you have to import and I can not use it.

    
asked by Luis Dominguez 22.04.2018 в 15:07
source

2 answers

1

Here is an example of how to do it, I just tried it.

Event load of the form

       private void Form1_Load(object sender, EventArgs e)
       {
            var dt = new DataTable();
            dt.Columns.Add("Nombre");
            dt.Columns.Add("Edad");
            dt.Columns.Add("Cedula de la persona");

            dt.Rows.Add("Nombre 1",12,"239847893-4565464");
            dt.Rows.Add("Nombre 2", 16, "23se59847893-4565464");


            dataGridView1.AutoSizeColumnsMode = 
            DataGridViewAutoSizeColumnsMode.Fill;

            dataGridView1.DataSource = dt;

       }

The first thing I did was create an example table, and create the structure with the columns.add method of the data table, then add several records with the rows.add method of the data table, to fill the data grid use the property data source of the datagrid and to adjust the column use the AutoSizeColumnsMode property of the data grid and assign it the enumerable DataGridViewAutoSizeColumnsMode with the value fill.

The person's ID column was automatically adjusted, and created with a large size for the test

    
answered by 22.04.2018 / 15:37
source
0

In case someone has the same problem and needs to do it with a datagrid it is solved like this:

       //cargo el datagrid 
        dataGrid1.ItemsSource = dt.DefaultView;

Now I modify the datagrid:

      double ncolumnas = Convert.ToDouble(dt.Columns.Count);
      double tamlargo = this.dataGrid1.ActualWidth;
    //ajusta el largo de cada columna 
        dataGrid1.ColumnWidth = tamlargo / ncolumnas;
    //quitar scroll 
        dataGrid1.HorizontalScrollBarVisibility= 0;
        dataGrid1.VerticalScrollBarVisibility = 0;
    //quita la que aparece con las flechas ojo no cambiar el header
        dataGrid1.RowHeaderWidth = 0;
    
answered by 23.04.2018 в 14:56