How to predefine columns in a DataGrid filled with data from a database?


I want to give an already defined style of columns with their title and everything to a DataGrid, I present the records of a table called users where I use the following code made from C # with Visual Studio 2017

public void mostrarTabla()
        String consulta = "select Nombre,ApellidoP,ApellidoM,Sexo,Telefono,Edad,Puesto from usuarios;";
        SqlDataAdapter dataAdapter = new SqlDataAdapter(consulta,new BaseDeDatos().obtenerConexion());
        DataSet ds = new DataSet();
        dataGridUsuarios.ItemsSource = ds.Tables[0].DefaultView;

It shows me the data with the name of the correct columns but everything is very close and aesthetically bad .. and I can not find in the configuration provided by Visual Studio for the code nothing to improve it

asked by Richard Yordy 07.04.2018 в 21:38

3 answers


I'll explain it to you by the interface form.

First we create the DataGrid , after that we have a button in the upper right part (arrow type), when we click on it, a menu is displayed where we have the option of edit column ( edit column):

by clicking and a new window will appear where you can create your columns:

You add as many columns as you need, once created you select them one by one to give them a size defined with the width property.

For example, I gave him 120 for his first and last name, 80 for sex and 70 for age.

answered by 08.04.2018 / 00:50

I think what you need is to configure the table so that it is automatically filled in or adjusted to the title or content of the columns. in that order of ideas perhaps this configuration will serve you.

answered by 07.04.2018 в 23:17

You can do it with the Columns property like this:

dataGridUsuarios.Columns(0).Width = 100;
dataGridUsuarios.Columns(1).Width = 150;

And so with the rest of the columns, the collection of columns always starts at zero for the first item


answered by 07.04.2018 в 22:01