从数据库读取数据到datatable,使用linq处理后,在datagridview显示
时间: 2024-04-30 07:21:08 浏览: 74
可以按照以下步骤操作:
1. 建立与数据库的连接并执行查询语句,将结果存储在DataTable中:
```csharp
string connectionString = "your_connection_string";
string query = "SELECT * FROM your_table";
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}
```
2. 使用LINQ查询语句对DataTable进行处理,例如筛选出符合条件的数据:
```csharp
var filteredData = from row in dataTable.AsEnumerable()
where row.Field<string>("column_name") == "condition_value"
select row;
```
3. 将处理后的数据绑定到DataGridView控件上:
```csharp
dataGridView.DataSource = filteredData.ToList();
```
完整的代码示例:
```csharp
string connectionString = "your_connection_string";
string query = "SELECT * FROM your_table";
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(dataTable);
}
var filteredData = from row in dataTable.AsEnumerable()
where row.Field<string>("column_name") == "condition_value"
select row;
dataGridView.DataSource = filteredData.ToList();
```
阅读全文