如何:将数据绑定到 Windows 窗体 DataGridView 控件
2012-05-06 01:24
831 查看
如何:将数据绑定到 Windows 窗体 DataGridView 控件
.NET Framework 2.0其他版本
![](http://i.msdn.microsoft.com/Areas/Brand/Content/Msdn_ImageSprite.png)
18(共 22)对本文的评价是有帮助 - 评价此主题
DataGridView 控件支持标准 Windows 窗体数据绑定模型,因此可绑定到各种数据源。但在多数情况下,都将绑定到一个 BindingSource 组件,由该组件来管理与数据源交互的详细信息。BindingSource 组件可表示任何
Windows 窗体数据源,并在选择或修改数据位置时提供很大的灵活性。有关 DataGridView 控件支持的数据源的更多信息,请参见DataGridView 控件概述(Windows 窗体)。
Visual Studio 中对此任务提供了广泛的支持。 如何:使用设计器将数据绑定到 Windows 窗体的 DataGridView 控件
如何:使用设计器将数据绑定到 Windows 窗体的 DataGridView 控件
如何:使用设计器将数据绑定到 Windows 窗体的 DataGridView 控件
如何:使用设计器将数据绑定到 Windows 窗体的 DataGridView 控件
过程
将 DataGridView 控件连接到数据
实现一个用于处理数据库数据检索的详细信息的方法。下面的代码示例实现一个 GetData 方法,该方法对一个 SqlDataAdapter 组件进行初始化,并使用该组件填充DataTable。然后,将 DataTable 绑定到 BindingSource 组件。请确保将 connectionString 变量的值设置为与数据库相应的值。您将需要访问安装了Northwind SQL Server 示例数据库的服务器。
C#
C++
VB
private void GetData(string selectCommand) { try { // Specify a connection string. Replace the given value with a // valid connection string for a Northwind SQL Server sample // database accessible to your system. String connectionString = "Integrated Security=SSPI;Persist Security Info=False;" + "Initial Catalog=Northwind;Data Source=localhost"; // Create a new data adapter based on the specified query. dataAdapter = new SqlDataAdapter(selectCommand, connectionString); // Create a command builder to generate SQL update, insert, and // delete commands based on selectCommand. These are used to // update the database. SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); // Populate a new data table and bind it to the BindingSource. DataTable table = new DataTable(); table.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(table); bindingSource1.DataSource = table; // Resize the DataGridView columns to fit the newly loaded content. dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); } catch (SqlException) { MessageBox.Show("To run this example, replace the value of the " + "connectionString variable with a connection string that is " + "valid for your system."); } }
在窗体的 Load 事件处理程序中,将 DataGridView 控件绑定到 BindingSource 组件,并调用 GetData 方法从数据库中检索数据。
C#
C++
VB
private void Form1_Load(object sender, System.EventArgs e) { // Bind the DataGridView to the BindingSource // and load the data from the database. dataGridView1.DataSource = bindingSource1; GetData("select * from Customers"); }
示例
下面的完整代码示例提供的按钮用于从数据库重新加载数据和向数据库提交更改。C#
C++
VB
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public class Form1 : System.Windows.Forms.Form
{
private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();
private SqlDataAdapter dataAdapter = new SqlDataAdapter();
private Button reloadButton = new Button();
private Button submitButton = new Button();
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
// Initialize the form.
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
reloadButton.Text = "reload";
submitButton.Text = "submit";
reloadButton.Click += new System.EventHandler(reloadButton_Click);
submitButton.Click += new System.EventHandler(submitButton_Click);
FlowLayoutPanel panel = new FlowLayoutPanel();
panel.Dock = DockStyle.Top;
panel.AutoSize = true;
panel.Controls.AddRange(new Control[] { reloadButton, submitButton });
this.Controls.AddRange(new Control[] { dataGridView1, panel });
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView databinding and updating demo";
}
private void Form1_Load(object sender, System.EventArgs e) { // Bind the DataGridView to the BindingSource // and load the data from the database. dataGridView1.DataSource = bindingSource1; GetData("select * from Customers"); }private void reloadButton_Click(object sender, System.EventArgs e)
{
// Reload the data from the database.
GetData(dataAdapter.SelectCommand.CommandText);
}
private void submitButton_Click(object sender, System.EventArgs e)
{
// Update the database with the user's changes.
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
private void GetData(string selectCommand) { try { // Specify a connection string. Replace the given value with a // valid connection string for a Northwind SQL Server sample // database accessible to your system. String connectionString = "Integrated Security=SSPI;Persist Security Info=False;" + "Initial Catalog=Northwind;Data Source=localhost"; // Create a new data adapter based on the specified query. dataAdapter = new SqlDataAdapter(selectCommand, connectionString); // Create a command builder to generate SQL update, insert, and // delete commands based on selectCommand. These are used to // update the database. SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); // Populate a new data table and bind it to the BindingSource. DataTable table = new DataTable(); table.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(table); bindingSource1.DataSource = table; // Resize the DataGridView columns to fit the newly loaded content. dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); } catch (SqlException) { MessageBox.Show("To run this example, replace the value of the " + "connectionString variable with a connection string that is " + "valid for your system."); } }}
编译代码
此示例需要:对 System、System.Windows.Forms、System.Data 和 System.XML 程序集的引用。
安全
将敏感信息(如密码)存储在连接字符串中可能会影响您的应用程序的安全性。若要控制对数据库的访问,一种较为安全的方法是使用 Windows 身份验证(也称为集成安全性)。有关更多信息,请参见保护连接字符串。
请参见
参考
DataGridViewSystem.Windows.Forms.DataGridView.DataSource
BindingSource
其他资源
在 Windows 窗体 DataGridView 控件中显示数据保护连接字符串
相关文章推荐
- 来自MSDN的一个Sample:如何自定义 Windows 窗体 DataGridView 控件中的数据格式设置
- 将数据绑定到 Windows 窗体 DataGridView 控件
- 如何:在 Windows 窗体 DataGridView 单元格中承载控件
- 如何把Windows 窗体 DataGridView 的某一列的数据显示为“*”
- 如何:从 Windows 窗体 DataGridView 控件中移除自动生成的列
- 将字符串值的数据表数据绑定到 Windows 窗体 DataGrid 控件 (Visual Basic)
- 如何:为 Windows 窗体 DataGridView 控件中的新行指定默认值
- C# 如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮 Enable = false
- 在 Windows 窗体 DataGridView 控件中实现实时数据加载的虚拟模式
- 如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮
- 如何:禁用 Windows 窗体 DataGridView 控件的按钮列中的按钮(摘录)
- 如何把Windows 窗体 DataGridView 的某一列的数据显示为“*”。
- 如何:访问绑定到 Windows 窗体 DataGridView 行的对象
- 处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误
- 『转MSDN』如何:在 Windows 窗体 DataGridView 单元格中承载日历控件
- 创建未绑定的 Windows 窗体 DataGridView 控件
- 实现虚拟模式的动态数据加载Windows窗体DataGridView控件 .net 4.5 (一)
- 如何将字典Dictionary数据绑定到DataGridView控件上
- 如何:操作 Windows 窗体 DataGridView 控件中的列
- C#中,datagridview与sql数据源绑定后,通过控件更改数据如何自动回写更新到数据源