完成DataGrid控件与Sql Server连接
时间: 2023-12-03 13:45:33 浏览: 90
要连接DataGrid控件与Sql Server数据库,需要以下步骤:
1. 添加SqlConnection对象并设置连接字符串。连接字符串包含有关数据库服务器和其他连接参数的信息。例如:
```csharp
SqlConnection connection = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;");
```
2. 创建SqlCommand对象并设置SQL查询。例如:
```csharp
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
```
3. 创建SqlDataAdapter对象并使用SqlCommand对象执行查询。例如:
```csharp
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
```
4. 将DataTable对象绑定到DataGrid控件。例如:
```csharp
dataGrid1.ItemsSource = dataTable.DefaultView;
```
完整代码示例:
```csharp
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Controls;
using System.Data;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SqlConnection connection = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;");
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
dataGrid1.ItemsSource = dataTable.DefaultView;
}
}
}
```
注意:在实际应用程序中,连接字符串应该存储在配置文件中,并且不应在代码中硬编码。此外,还要确保在查询中使用正确的表名和列名。
阅读全文