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:
i otrzymuje wynik:
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:
CodePudding user response:
There are a few ways how to do it:
Make a complex SQL Query, that will group the data as it's needed, using Joins and other ways of data union.
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.
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)