Как datagrid подключить к бд
Перейти к содержимому

Как datagrid подключить к бд

  • автор:

Пошаговое руководство. Отображение данных из базы данных SQL Server в элементе управления DataGrid

В этом пошаговом руководстве, получения данных из базы данных SQL Server и отображение их в DataGrid элемента управления. Использовать ADO.NET Entity Framework для создания классов сущностей, которые представляют данные и использовать LINQ для записи запроса, который получает указанные данные из класса сущностей.

Предварительные требования

Ниже приведены компоненты, необходимые для выполнения данного пошагового руководства.

Доступ к запущенному экземпляру SQL Server или SQL Server Express с образца базы данных AdventureWorks, подключенные к ней. Можно загрузить из базы данных AdventureWorks GitHub.

Создайте классы сущностей

Создайте новый проект приложения WPF в Visual Basic или C# и назовите его DataGridSQLExample .

В обозревателе решений щелкните правой кнопкой мыши проект, выберите пункт добавить, а затем выберите новый элемент.

Будет открыто диалоговое окно Добавление нового элемента.

На панели "Установленные шаблоны", выберите данных и в списке шаблонов выберите ADO.NET Entity Data Model.

Шаблон элемента модели EDM ADO.NET

Назовите файл AdventureWorksModel.edmx и нажмите кнопку добавить.

Появится мастер модели EDM.

На экране «Выбор содержимого модели» выберите конструктор EF из базы данных и нажмите кнопку Далее.

На экране «Выбор подключения к данным» обеспечивают подключение к базе данных AdventureWorksLT2008. Дополнительные сведения см. в разделе выберите Your данных диалогового окна соединения.

Убедитесь, что имя указано AdventureWorksLT2008Entities и что сохранить настройки подключения сущности в App.Config как флажок выбран и нажмите кнопку Далее.

На экране «Выбор объектов базы данных» разверните узел таблицы и выберите продукта и ProductCategory таблиц.

Можно создавать классы сущностей для всех таблиц; Тем не менее в этом примере извлекаются данные только из этих двух таблиц.

Выбор пунктов Product и ProductCategory из таблиц

Нажмите кнопку Готово.

Сущности Product и ProductCategory, отображаются в конструкторе сущностей.

Модели сущностей Product и ProductCategory

Извлечение и представление данных

Откройте файл MainWindow.xaml.

Задайте Width свойство Window для 450.

В редакторе XAML добавьте следующий DataGrid тег между <Grid> и </Grid> теги для добавления DataGrid с именем dataGrid1 .

Окно с DataGrid

С помощью окна свойств или редактор XAML, создайте обработчик событий для Window с именем Window_Loaded для Loaded событий. Дополнительные сведения см. в разделе Как Создание простого обработчика событий.

Ниже показан XAML для MainWindow.xaml.

Если вы используете Visual Basic, в первой строке файла MainWindow.XAML, замените x:Class="DataGridSQLExample.MainWindow" с x:Class="MainWindow" .

Откройте файл с выделенным кодом (MainWindow.xaml.vb или MainWindow.xaml.cs) для Window.

Добавьте следующий код, чтобы получить только определенные значения из соединяемых таблиц и задать ItemsSource свойство DataGrid к результатам запроса.

How can I bind an SQL Query to a DataGrid?

Using the Code-behind, when my WPF loads, I end up with 3 columns instead of 2. I want the 1st column to be the Checkbox (enabled from SQL query) and the proxyFor is a String that I want in the 2nd Column.

1 Answer 1

You need to set DataGrid.AutoGenerateColumns to False , to prevent it from automatically generating the columns. Then you need to explicitly bind the columns that you defined yourself. DataGridCheckBoxColumn and DataGridTextColumn both have other properties you can set as well, to further customize what you see in the grid.

If the checkbox column doesn’t work the way you want, you could try writing a value converter to convert between your integer and a boolean.

If that doesn’t work, you’ll need to use a DataGridTemplateColumn instead, which will give you a lot more power to control what the column looks like and how it works.

In answer to your first question, «Is there a way to load the SQL query and bind it directly with the DataGrid?», I’m not sure exactly what that means: Are you asking if you can assign a SQL string to some property of DataGrid and have it execute the query and populate itself? No. You could write an attached property to do that, if you really wanted to. That might be fun.

Another point, which you didn’t ask about but ought to be mentioned:

If you already know that’s bad practice and you’re planning to replace it once you get the code working, then you don’t need to hear this, but in case that’s not so, you should really make an absolute habit of using parameters:

What if somebody has a single quote in his user name? It can happen. And if you use simple concatenation of SQL strings in externally-facing code, you’re allowing anybody on Earth to run arbitrary SQL in your database.

Why do you have ItemsSource=»» in the XAML? That will bind the DataGrid’s DataContext to ItemsSource. If your view has a viewmodel, that DataContext should be the viewmodel; otherwise, it’s probably null. And you’re assigning something else in code behind anyhow.

Source libre

I keep getting "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records" everytime I make a change and it calls mySqlDataAdapter.Update . any ideas?

Nice article. Unfortunately, I can't use it because I have no idea why some website named 4shared.com is wanting to download an executable to my computer. Silly. Why put the code in a large text box or provide a link to a text file or ZIP file or anything simple?

How do I hide the first column, that contains table primary key? I don't want to show it in the dgw.

Find here a complete. C# Datagridview Tutorial.

This error occurred highlighting this line: mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();

ERROR:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

Additional information: The DataAdapter.SelectCommand property needs to be initialized.

Nice tutorial , Thank you so much.

You save my life. Thanks

How would I parameterize the query and update the GridView when I change an input?

An Answer for:
This error occurred highlighting this line: mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();

ERROR:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

Additional information: The DataAdapter.SelectCommand property needs to be initialized.

SET PRIMARY KEY FIELD FOR TABLE

Thank you.
But my code occur concurrency exception like above people's comments.
I checked my table in database, the table has field include primary key.
how to solve this problem?

my table property is below

CREATE TABLE tblData
(
ScheduleName VARCHAR(255),
StepNo INT(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
Type VARCHAR(32) NOT NULL ,
Volt FLOAT(11) unsigned NOT NULL ,
Current FLOAT(11) unsigned NOT NULL ,
cutoff_time TIME(3 ),
modified_time TIMESTAMP(2)
);

some data inserted by below query
insert into tbldata values ("my_schedule", NULL, "charge" , 1.23, 45.8, "11:22:33.456" , NOW () );

Load Datagridview From Database C#

In this article, you can learn about how to load datagridview from database C#. C# datagridview load data from database Mysql. This tutorial takes a specific table from a database and display it on a DataGridView. This is done with a DataReader and data logic. A visual representation of data is the end result.

Let’s following this step for know to load data in Datagridview:

  1. Create database in mysql with name “test” and create table with name “user”, like the below.

2. Create a new application project. In Visual Studio, on the menu click File> New > Project. For more details, see the following menu on the display.

3. Then will appear the window New Project like the look below.

4. Write down the name of the project that will be created on a field Name. Specify the directory storage project by accessing the field Location. Next, give the name of the solution in the Solution Name. Then click OK.

5. Create a new windows form like the below.

6. Create a new class for connection database and write the following program listing :

7. Next step, Back to windows form and view code to write the following program listing:

8. After you write down the program listings, press the F5 key to run the program and if you successfull connect your database the result is :

We have explained how to make program c# datagridview load data from database, for those of you who want to download the source code of the program also can. Hopefully this discussion is helpful to you.

You can see Load Datagridview From Database C# from Github project in Here.

Thank you for reading this article about Load Datagridview From Database C#, I hope this article is useful for you. Visit My Github about .Net Csharp in Here

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *