Home > Back-end >  Add new column in datagridview1 with a completely new sort of SQL Server database data
Add new column in datagridview1 with a completely new sort of SQL Server database data

Time:11-24

I create a small program using a SQL Server database and C#.

I connected to the database and sort all data and display it in a datagridview1 without any problems.

My code:

enter image description here

i otrzymuje wynik:

enter image description here

Now my question: how can I add a new column in datagridview1 with a completely new sort of SQL Server database data?

CodePudding user response:

obviously a sort order is part of a SQL expression and you do not mean that, as you would surely already know (?) instead change how it sorts, which is the collation of the column. This is thankfully fully supported:

https://docs.microsoft.com/en-us/sql/relational-databases/collations/set-or-change-the-column-collation?view=sql-server-ver15

CodePudding user response:

There are a few ways how to do it:

  1. Make a complex SQL Query, that will group the data as it's needed, using Joins and other ways of data union.

  2. The easiest and the worst way how to do it - is to extend your data table manually:

    dataTable.Columns.Add(new DataColumn("newColumn", typeof(string)));
    

This will automatically refresh DataGridView on the form. And then you will need to add new data to the new DataTable column manually.

  1. I prefer to work with dataGridView based on models. You need to create a class - that will represent your model. Like class Person with properties: Name, Age, etc. And then set this list as data source.

     List<Person> listOfPersons = new();
     dataGridView1.AutoGenerateColumns = true;
     dataGridView1.DataSource = new BindingSource() { DataSource = listOfPersons};
    

The main problem - you will need to parse database data to the model format. Actually, this is where ORM (Object-Relational Mapping) is helpful. There are a few ready solutions, like Dapper. It will simplify your life)

  • Related