您的位置:首页 > 其它

将数据绑定到 Windows 窗体 DataGridView 控件

2009-04-13 10:32 756 查看
中国 - 简体中文


Argentina (Español)
Australia (English)
Brasil (Português)
Canada (English)
Canada (Français)
中国 (简体中文)
Colombia (Español)
Deutschland (Deutsch)
España (Español)
France (Français)
India (English)
Italia (Italiano)
日本 (日本語)
México (Español)
Perú (Español)
Россия (Pусский)
United Kingdom (English)
United States (English)
更多
Microsoft.com



产品家族

Office
Windows
Windows Server System
Windows Mobile
开发工具
商务管理解决方案(MBS)
MSN

产品资源

Microsoft Update
Office Update
下载中心
客户帮助与支持
安全性与隐私保护
微软中文社区
教育培训与认证
活动与培训

关于微软

微软总部
微软中国
新闻报道

热门栏目

MSDN
TechNet
企业用户
合作伙伴
硬件产品
所有产品
Microsoft.com 站点地图

欢迎您 登录



Suggestions

使用 Live Search 搜索
MSDNMicrosoft.com整个网站
Close

Microsoft 开发人员网络

主页

技术资源库

学习

下载

支持

社区



如何:将数据绑定到 Windows 窗体 DataGridView 控件

Windows 窗体编程
如何:将数据绑定到 Windows 窗体 DataGridView 控件

DataGridView 控件支持标准 Windows 窗体数据绑定模型,因此可绑定到各种数据源。但在多数情况下,都将绑定到一个 BindingSource 组件,由该组件来管理与数据源交互的详细信息。BindingSource 组件可表示任何 Windows 窗体数据源,并在选择或修改数据位置时提供很大的灵活性。有关 DataGridView 控件支持的数据源的更多信息,请参见 DataGridView 控件概述(Windows 窗体)

Visual Studio 中对此任务提供了广泛的支持。 有关更多信息,请参见如何:使用设计器将数据绑定到 Windows 窗体的 DataGridView 控件

过程

将 DataGridView 控件连接到数据

实现一个用于处理数据库数据检索的详细信息的方法。下面的代码示例实现一个 GetData 方法,该方法对一个 SqlDataAdapter 组件进行初始化,并使用该组件填充 DataTable。然后,将 DataTable 绑定到 BindingSource 组件。请确保将 connectionString 变量的值设置为与数据库相应的值。您将需要访问安装了 Northwind SQL Server 示例数据库的服务器。

Visual Basic


复制代码


Private Sub GetData(ByVal selectCommand As String)

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.
Dim connectionString As String = _
"Integrated Security=SSPI;Persist Security Info=False;" + _
"Initial Catalog=Northwind;Data Source=localhost"

' Create a new data adapter based on the specified query.
Me.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.
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)

' Populate a new data table and bind it to the BindingSource.
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table

' Resize the DataGridView columns to fit the newly loaded content.
Me.dataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try

End Sub


C#


复制代码


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.");
}
}


C++


复制代码


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 = gcnew 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.
gcnew SqlCommandBuilder(dataAdapter);

// Populate a new data table and bind it to the BindingSource.
DataTable^ table = gcnew DataTable();
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 方法从数据库中检索数据。

Visual Basic


复制代码


Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load

' Bind the DataGridView to the BindingSource
' and load the data from the database.
Me.dataGridView1.DataSource = Me.bindingSource1
GetData("select * from Customers")

End Sub


C#


复制代码


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++


复制代码


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");
}


示例

下面的完整代码示例提供的按钮用于从数据库重新加载数据和向数据库提交更改。

Visual Basic


复制代码


Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class Form1
Inherits System.Windows.Forms.Form

Private dataGridView1 As New DataGridView()
Private bindingSource1 As New BindingSource()
Private dataAdapter As New SqlDataAdapter()
Private WithEvents reloadButton As New Button()
Private WithEvents submitButton As New Button()

<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub

' Initialize the form.
Public Sub New()

Me.dataGridView1.Dock = DockStyle.Fill

Me.reloadButton.Text = "reload"
Me.submitButton.Text = "submit"

Dim panel As New FlowLayoutPanel()
panel.Dock = DockStyle.Top
panel.AutoSize = True
panel.Controls.AddRange(New Control() {Me.reloadButton, Me.submitButton})

Me.Controls.AddRange(New Control() {Me.dataGridView1, panel})
Me.Text = "DataGridView databinding and updating demo"

End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load ' Bind the DataGridView to the BindingSource ' and load the data from the database. Me.dataGridView1.DataSource = Me.bindingSource1 GetData("select * from Customers") End Sub
Private Sub reloadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles reloadButton.Click

' Reload the data from the database.
GetData(Me.dataAdapter.SelectCommand.CommandText)

End Sub

Private Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles submitButton.Click

' Update the database with the user's changes.
Me.dataAdapter.Update(CType(Me.bindingSource1.DataSource, DataTable))

End Sub

Private Sub GetData(ByVal selectCommand As String) 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. Dim connectionString As String = _ "Integrated Security=SSPI;Persist Security Info=False;" + _ "Initial Catalog=Northwind;Data Source=localhost" ' Create a new data adapter based on the specified query. Me.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. Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter) ' Populate a new data table and bind it to the BindingSource. Dim table As New DataTable() table.Locale = System.Globalization.CultureInfo.InvariantCulture Me.dataAdapter.Fill(table) Me.bindingSource1.DataSource = table ' Resize the DataGridView columns to fit the newly loaded content. Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) Catch ex As SqlException MessageBox.Show("To run this example, replace the value of the " + _ "connectionString variable with a connection string that is " + _ "valid for your system.") End Try End Sub
End Class


C#


复制代码


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."); } }
}


C++


复制代码


#using <System.Data.dll>
#using <System.Transactions.dll>
#using <System.EnterpriseServices.dll>
#using <System.Xml.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;

public ref class Form1 : public System::Windows::Forms::Form
{
private:
DataGridView^ dataGridView1;
private:
BindingSource^ bindingSource1;
private:
SqlDataAdapter^ dataAdapter;
private:
Button^ reloadButton;
private:
Button^ submitButton;

public:
static void Main()
{
Application::Run(gcnew Form1());
}

// Initialize the form.
public:
Form1()
{
dataGridView1 = gcnew DataGridView();
bindingSource1 = gcnew BindingSource();
dataAdapter = gcnew SqlDataAdapter();
reloadButton = gcnew Button();
submitButton = gcnew Button();

dataGridView1->Dock = DockStyle::Fill;

reloadButton->Text = "reload";
submitButton->Text = "submit";
reloadButton->Click += gcnew System::EventHandler(this,&Form1::reloadButton_Click);
submitButton->Click += gcnew System::EventHandler(this,&Form1::submitButton_Click);

FlowLayoutPanel^ panel = gcnew FlowLayoutPanel();
panel->Dock = DockStyle::Top;
panel->AutoSize = true;
panel->Controls->AddRange(gcnew array<Control^> { reloadButton, submitButton });

this->Controls->AddRange(gcnew array<Control^> { dataGridView1, panel });
this->Load += gcnew System::EventHandler(this,&Form1::Form1_Load);
}

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"); }
void reloadButton_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
{
// Reload the data from the database.
GetData(dataAdapter->SelectCommand->CommandText);
}

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 = gcnew 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. gcnew SqlCommandBuilder(dataAdapter); // Populate a new data table and bind it to the BindingSource. DataTable^ table = gcnew DataTable(); 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."); } }};


编译代码

此示例需要:

SystemSystem.Windows.FormsSystem.DataSystem.XML 程序集的引用。

安全

将敏感信息(如密码)存储在连接字符串中可能会影响您的应用程序的安全性。若要控制对数据库的访问,一种较为安全的方法是使用 Windows 身份验证(也称为集成安全性)。有关更多信息,请参见保护连接字符串

请参见

参考

DataGridView
System.Windows.Forms.DataGridView.DataSource
BindingSource

其他资源

在 Windows 窗体 DataGridView 控件中显示数据
保护连接字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐