datagrid数据绑定的概念

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了datagrid数据绑定的概念相关的知识,希望对你有一定的参考价值。

最近小弟刚接触asp.net,对datagrid数据绑定的概念不是很清楚,什么是数据绑定呢?
在ASP中查询,只是放到<TABLE>中啊?
期待大家的回答,谢谢

参考技术A datagrid就是一个数据绑定控件,可以用手写属性也可以在属性面版里更改。,具体自己去看书吧, 参考技术B 在可滚动的网格中显示 ADO .NET 数据。

有关此类型所有成员的列表,请参阅 DataGrid 成员。

System.Object
System.MarshalByRefObject
System.ComponentModel.Component
System.Windows.Forms.Control
System.Windows.Forms.DataGrid

[Visual Basic]
Public Class DataGrid
Inherits Control
Implements ISupportInitialize

[C#]
public class DataGrid : Control, ISupportInitialize

[C++]
public __gc class DataGrid : public Control, ISupportInitialize

[JScript]
public class DataGrid extends Control implements ISupportInitialize

线程安全
此类型的所有公共静态(Visual Basic 中为 Shared)成员对多线程操作而言都是安全的。但不保证任何实例成员是线程安全的。

备注
System.Windows.Forms.DataGrid 显示指向子表的类似 Web 的链接。您可以单击链接定位到子表。在显示子表时,标题中显示后退按钮,可以单击它向后定位到父表。父行的数据显示在标题下面、列标头的上面。可以通过单击后退按钮右边的按钮来隐藏父行信息。

若要在运行时在 System.Windows.Forms.DataGrid 中显示表,请使用 SetDataBinding 方法将 DataSource 和 DataMember 属性设置为有效的数据源。下列数据源有效:

DataTable
DataView
DataSet
DataViewManager
一维数组
任何实现 IListSource 接口的组件
任何实现 IList 接口的组件
有关 DataSet 类的更多信息,请参见创建和使用 DataSet。

通过将 DataView 用作数据源并将 AddNew 属性设置为 false,可以创建网格,该网格允许用户编辑数据但阻止他们添加新行。

数据源可通过 BindingManagerBase 对象进一步进行管理。对于数据源中的每个表,均可从窗体的 BindingContext 中返回一个 BindingManagerBase。例如,可通过返回关联的 BindingManagerBase 对象的 Count 属性来确定数据源所包含的行数。

若要验证数据,请使用代表数据及其事件的基础对象。例如,如果数据来自 DataSet 中的 DataTable,则可使用 ColumnChanging 和 RowChanging 事件。

注意 由于可以自定义列数(通过添加或删除 GridColumnStylesCollection 的成员),而且可以按列对行进行排序,因此不能确保 RowNumber 和 ColumnNumber 属性值与 DataTable 中的 DataRow 和 DataColumn 索引相符。因此,请避免在 Validating 事件中使用这些属性来验证数据。
若要确定所选择的单元格,请使用 CurrentCell 属性。可使用 Item 属性更改任意单元格的值,该属性可采用单元格的行索引和列索引或单个 DataGridCell。监视 CurrentCellChanged 事件以检测用户选择另一个单元格的时间。

若要确定用户所单击的控件的部分,请使用 MouseDown 事件中的 HitTest 方法。HitTest 方法返回一个 DataGrid.HitTestInfo 对象,该对象包含被单击区域的行和列。

若要在运行时管理控件的外观,有多个可用于设置颜色和标题属性的属性,包括 CaptionForeColor、CaptionBackColor、CaptionFont 等等。

可进一步修改所显示网格的外观,方法是创建 DataGridTableStyle 对象,并将它们添加到 GridTableStylesCollection 中,可通过 TableStyles 属性访问后者。例如,如果 DataSource 设置为包含三个 DataTable 对象的 DataSet,则可以向该集合添加三个 DataGridTableStyle 对象,每个表一个。若要将每个 DataGridTableStyle 对象与一个 DataTable 同步,请将 DataGridTableStyle 的 MappingName 设置为 DataTable 的 TableName。有关绑定到对象数组的详细信息,请参见 DataGridTableStyle.MappingName 属性。

要创建表的自定义视图,请创建 DataGridTextBoxColumn 或 DataGridBoolColumn 类的一个实例,并将该对象添加到通过 TableStyles 属性访问的 GridTableStylesCollection 中。两个类都从 DataGridColumnStyle 继承。对于各列的样式,请将 MappingName 设置成要在网格中显示的列的 ColumnName。若要隐藏某列,请将其 MappingName 设置为除有效 ColumnName 之外的内容。

要设置列的文本格式,请将 DataGridTextBoxColumn 的 Format 属性设置成日期与时间格式字符串或标准数字格式字符串中的某个值。

要将 DataGrid 绑定到对象的强类型数组,该对象必须包含公共属性。要创建可显示这类数组的 DataGridTableStyle,请将 DataGridTableStyle.MappingName 属性设置为 classname[],其中 classname 将被类名替换。另外还要注意 MappingName 属性须区分大小写。有关示例,请参见 MappingName 属性。

也可以将 DataGrid 绑定到 ArrayList。ArrayList 的一个功能是它可以包含多种类型的对象,但当列表中的所有项与第一项具有相同的类型时,DataGrid 只能绑定到这类列表。这意味着所有的对象必须是同一种类型,或者必须从与列表中第一项相同的类继承。例如,如果列表中的第一项为 Control,则第二项可能为 TextBox(它从 Control 继承)。另一方面,如果第一项为 TextBox,则第二个对象就不可能是 Control。此外,ArrayList 在绑定时必须包含项目。空 ArrayList 会导致空网格。当绑定到 ArrayList 时,请将 DataGridTableStyle 的 MappingName 设置为“ArrayList”(类型名)。

对于每个 DataGridTableStyle,都可以设置颜色和标题属性来重写 System.Windows.Forms.DataGrid 控件的设置。但是,如果未设置上述属性,则默认情况下使用控件的设置。可以通过 DataGridTableStyle 属性重写下列属性:

AllowSorting
AlternatingBackColor
BackColor
ColumnHeadersVisible
ForeColor
GridLineColor
GridLineStyle
HeaderBackColor
HeaderFont
HeaderForeColor
LinkColor
PreferredColumnWidth
PreferredRowHeight
ReadOnly
RowHeadersVisible
RowHeaderWidth
SelectionBackColor
SelectionForeColor
若要自定义单个列的外观,请将 DataGridColumnStyle 对象添加到 GridColumnStylesCollection 中,后者可以通过每个 DataGridTableStyle 的 GridColumnStyles 属性来访问。若要使每个 DataGridColumnStyle 与 DataTable 中的一个 DataColumn 同步,请将 MappingName 设置为某 DataColumn 的 ColumnName。在构造 DataGridColumnStyle 时,还可以设置指定列显示数据的方式的格式化字符串。例如,可以指定列使用短日期格式显示表中所包含的日期。

警告 在向 GridTableStylesCollection 添加 DataGridTableStyle 对象之前,始终应先创建 DataGridColumnStyle 对象并将其添加到 GridColumnStylesCollection。在向集合添加空的 DataGridTableStyle 时,将自动生成 DataGridColumnStyle 对象。因此,如果试图向 GridColumnStylesCollection 添加带有重复 MappingName 值的 DataGridColumnStyle 新对象时,将引发异常。
示例
[Visual Basic, C#, JScript] 下面的示例创建一个 Windows 窗体、包含两个 DataTable 对象的一个 DataSet 和关联这两个表的一个 DataRelation。若要显示数据,请随后通过 SetDataBinding 方法将一个 System.Windows.Forms.DataGrid 控件绑定到 DataSet。通过创建两个 DataGridTableStyle 对象并将每个对象的 MappingName 设置为 DataTable 对象之一的 TableName,窗体上的某按钮可更改网格的外观。该示例还在 MouseUp 事件中包含代码,使用 HitTest 方法来输出所单击的行、列和网格的部分。

[Visual Basic]
Option Explicit
Option Strict

Imports System
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
Inherits System.Windows.Forms.Form
Private components As System.ComponentModel.Container
Private button1 As Button
Private button2 As Button
Private myDataGrid As DataGrid
Private myDataSet As DataSet
Private TablesAlreadyAdded As Boolean

Public Sub New()
' Required for Windows Form Designer support.
InitializeComponent()
' Call SetUp to bind the controls.
SetUp()
End Sub

Private Sub InitializeComponent()
' Create the form and its controls.
Me.components = New System.ComponentModel.Container()
Me.button1 = New System.Windows.Forms.Button()
Me.button2 = New System.Windows.Forms.Button()
Me.myDataGrid = New DataGrid()

Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.Text = "DataGrid Control Sample"
Me.ClientSize = New System.Drawing.Size(450, 330)

button1.Location = New Point(24, 16)
button1.Size = New System.Drawing.Size(120, 24)
button1.Text = "Change Appearance"
AddHandler button1.Click, AddressOf button1_Click

button2.Location = New Point(150, 16)
button2.Size = New System.Drawing.Size(120, 24)
button2.Text = "Get Binding Manager"
AddHandler button2.Click, AddressOf button2_Click

myDataGrid.Location = New Point(24, 50)
myDataGrid.Size = New Size(300, 200)
myDataGrid.CaptionText = "Microsoft DataGrid Control"
AddHandler myDataGrid.MouseUp, AddressOf Grid_MouseUp

Me.Controls.Add(button1)
Me.Controls.Add(button2)
Me.Controls.Add(myDataGrid)
End Sub

Public Shared Sub Main()
Application.Run(New Form1())
End Sub

Private Sub SetUp()
' Create a DataSet with two tables and one relation.
MakeDataSet()
' Bind the DataGrid to the DataSet. The dataMember
' specifies that the Customers table should be displayed.
myDataGrid.SetDataBinding(myDataSet, "Customers")
End Sub

Protected Sub button1_Click(sender As Object, e As System.EventArgs)
If TablesAlreadyAdded = true then exit sub
AddCustomDataTableStyle()
End Sub

Private Sub AddCustomDataTableStyle()
Dim ts1 As New DataGridTableStyle()
ts1.MappingName = "Customers"
' Set other properties.
ts1.AlternatingBackColor = Color.LightGray
' Add a GridColumnStyle and set its MappingName
' to the name of a DataColumn in the DataTable.
' Set the HeaderText and Width properties.

Dim boolCol As New DataGridBoolColumn()
boolCol.MappingName = "Current"
boolCol.HeaderText = "IsCurrent Customer"
boolCol.Width = 150
ts1.GridColumnStyles.Add(boolCol)

' Add a second column style.
Dim TextCol As New DataGridTextBoxColumn()
TextCol.MappingName = "custName"
TextCol.HeaderText = "Customer Name"
TextCol.Width = 250
ts1.GridColumnStyles.Add(TextCol)

' Create the second table style with columns.
Dim ts2 As New DataGridTableStyle()
ts2.MappingName = "Orders"

' Set other properties.
ts2.AlternatingBackColor = Color.LightBlue

' Create new ColumnStyle objects
Dim cOrderDate As New DataGridTextBoxColumn()
cOrderDate.MappingName = "OrderDate"
cOrderDate.HeaderText = "Order Date"
cOrderDate.Width = 100
ts2.GridColumnStyles.Add(cOrderDate)

' Use a PropertyDescriptor to create a formatted
' column. First get the PropertyDescriptorCollection
' for the data source and data member.
Dim pcol As PropertyDescriptorCollection = _
Me.BindingContext(myDataSet, "Customers.custToOrders"). _
GetItemProperties()

' Create a formatted column using a PropertyDescriptor.
' The formatting character "c" specifies a currency format. */

Dim csOrderAmount As _
New DataGridTextBoxColumn(pcol("OrderAmount"), "c", True)
csOrderAmount.MappingName = "OrderAmount"
csOrderAmount.HeaderText = "Total"
csOrderAmount.Width = 100
ts2.GridColumnStyles.Add(csOrderAmount)

' Add the DataGridTableStyle instances to
' the GridTableStylesCollection.
myDataGrid.TableStyles.Add(ts1)
myDataGrid.TableStyles.Add(ts2)

' Sets the TablesAlreadyAdded to true so this doesn't happen again.
TablesAlreadyAdded = true
End Sub

Protected Sub button2_Click(sender As Object, e As System.EventArgs)
Dim bmGrid As BindingManagerBase
bmGrid = BindingContext(myDataSet, "Customers")
MessageBox.Show(("Current BindingManager Position: " & bmGrid.Position))
End Sub

Private Sub Grid_MouseUp(sender As Object, e As MouseEventArgs)
' Create a HitTestInfo object using the HitTest method.
' Get the DataGrid by casting sender.
Dim myGrid As DataGrid = CType(sender, DataGrid)
Dim myHitInfo As DataGrid.HitTestInfo = myGrid.HitTest(e.X, e.Y)
Console.WriteLine(myHitInfo)
Console.WriteLine(myHitInfo.Type)
Console.WriteLine(myHitInfo.Row)
Console.WriteLine(myHitInfo.Column)
End Sub

' Create a DataSet with two tables and populate it.
Private Sub MakeDataSet()
' Create a DataSet.
myDataSet = New DataSet("myDataSet")

' Create two DataTables.
Dim tCust As New DataTable("Customers")
Dim tOrders As New DataTable("Orders")

' Create two columns, and add them to the first table.
Dim cCustID As New DataColumn("CustID", GetType(Integer))
Dim cCustName As New DataColumn("CustName")
Dim cCurrent As New DataColumn("Current", GetType(Boolean))
tCust.Columns.Add(cCustID)
tCust.Columns.Add(cCustName)
tCust.Columns.Add(cCurrent)

' Create three columns, and add them to the second table.
Dim cID As New DataColumn("CustID", GetType(Integer))
Dim cOrderDate As New DataColumn("orderDate", GetType(DateTime))
Dim cOrderAmount As New DataColumn("OrderAmount", GetType(Decimal))
tOrders.Columns.Add(cOrderAmount)
tOrders.Columns.Add(cID)
tOrders.Columns.Add(cOrderDate)

' Add the tables to the DataSet.
myDataSet.Tables.Add(tCust)
myDataSet.Tables.Add(tOrders)

' Create a DataRelation, and add it to the DataSet.
Dim dr As New DataRelation("custToOrders", cCustID, cID)
myDataSet.Relations.Add(dr)

' Populates the tables. For each customer and order,
' creates two DataRow variables.
Dim newRow1 As DataRow
Dim newRow2 As DataRow

' Create three customers in the Customers Table.
Dim i As Integer
For i = 1 To 3
newRow1 = tCust.NewRow()
newRow1("custID") = i
' Add the row to the Customers table.
tCust.Rows.Add(newRow1)
Next i
' Give each customer a distinct name.
tCust.Rows(0)("custName") = "Customer1"
tCust.Rows(1)("custName") = "Customer2"
tCust.Rows(2)("custName") = "Customer3"

' Give the Current column a value.
tCust.Rows(0)("Current") = True
tCust.Rows(1)("Current") = True
tCust.Rows(2)("Current") = False

' For each customer, create five rows in the Orders table.
For i = 1 To 3
Dim j As Integer
For j = 1 To 5
newRow2 = tOrders.NewRow()
newRow2("CustID") = i
newRow2("orderDate") = New DateTime(2001, i, j * 2)
newRow2("OrderAmount") = i * 10 + j * 0.1
' Add the row to the Orders table.
tOrders.Rows.Add(newRow2)
Next j
Next i
End Sub
End Class

[C#]
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form

private System.ComponentModel.Container components;
private Button button1;
private Button button2;
private DataGrid myDataGrid;
private DataSet myDataSet;
private bool TablesAlreadyAdded;
public Form1()

// Required for Windows Form Designer support.
InitializeComponent();
// Call SetUp to bind the controls.
SetUp();


protected override void Dispose( bool disposing )
if( disposing )
if (components != null)
components.Dispose();

base.Dispose( disposing );

private void InitializeComponent()

// Create the form and its controls.
this.components = new System.ComponentModel.Container();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.myDataGrid = new DataGrid();

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.Text = "DataGrid Control Sample";
this.ClientSize = new System.Drawing.Size(450, 330);

button1.Location = new Point(24, 16);
button1.Size = new System.Drawing.Size(120, 24);
button1.Text = "Change Appearance";
button1.Click+=new System.EventHandler(button1_Click);

button2.Location = new Point(150, 16);
button2.Size = new System.Drawing.Size(120, 24);
button2.Text = "Get Binding Manager";
button2.Click+=new System.EventHandler(button2_Click);

myDataGrid.Location = new Point(24, 50);
myDataGrid.Size = new Size(300, 200);
myDataGrid.CaptionText = "Microsoft DataGrid Control";
myDataGrid.MouseUp += new MouseEventHandler(Grid_MouseUp);

this.Controls.Add(button1);
this.Controls.Add(button2);
this.Controls.Add(myDataGrid);


public static void Main()

Application.Run(new Form1());


private void SetUp()

// Create a DataSet with two tables and one relation.
MakeDataSet();
/* Bind the DataGrid to the DataSet. The dataMember
specifies that the Customers table should be displayed.*/
myDataGrid.SetDataBinding(myDataSet, "Customers");


protected void button1_Click(object sender, System.EventArgs e)

if(TablesAlreadyAdded) return;
AddCustomDataTableStyle();


private void AddCustomDataTableStyle()

DataGridTableStyle ts1 = new DataGridTableStyle();
ts1.MappingName = "Customers";
// Set other properties.
ts1.AlternatingBackColor = Color.LightGray;

/* Add a GridColumnStyle and set its MappingName
to the name of a DataColumn in the DataTable.
Set the HeaderText and Width properties. */

DataGridColumnStyle boolCol = new DataGridBoolColumn();
boolCol.MappingName = "Current";
boolCol.HeaderText = "IsCurrent Customer";
boolCol.Width = 150;
ts1.GridColumnStyles.Add(boolCol);

// Add a second column style.
DataGridColumnStyle TextCol = new DataGridTextBoxColumn();
TextCol.MappingName = "custName";
TextCol.HeaderText = "Customer Name";
TextCol.Width = 250;
ts1.GridColumnStyles.Add(TextCol);

// Create the second table style with columns.
DataGridTableStyle ts2 = new DataGridTableStyle();
ts2.MappingName = "Orders";

// Set other properties.
ts2.AlternatingBackColor = Color.LightBlue;

// Create new ColumnStyle objects
DataGridColumnStyle cOrderDate =
new DataGridTextBoxColumn();
cOrderDate.MappingName = "OrderDate";
cOrderDate.HeaderText = "Order Date";
cOrderDate.Width = 100;
ts2.GridColumnStyles.Add(cOrderDate);

/* Use a PropertyDescriptor to create a formatted
column. First get the PropertyDescriptorCollection
for the data source and data member. */
PropertyDescriptorCollection pcol = this.BindingContext
[myDataSet, "Customers.custToOrders"].GetItemProperties();

/* Create a formatted column using a PropertyDescriptor.
The formatting character "c" specifies a currency format. */
DataGridColumnStyle csOrderAmount =
new DataGridTextBoxColumn(pcol["OrderAmount"], "c", true);
csOrderAmount.MappingName = "OrderAmount";
csOrderAmount.HeaderText = "Total";
csOrderAmount.Width = 100;
ts2.GridColumnStyles.Add(csOrderAmount);

/* Add the DataGridTableStyle instances to
the GridTableStylesCollection. */
myDataGrid.TableStyles.Add(ts1);
myDataGrid.TableStyles.Add(ts2);

// Sets the TablesAlreadyAdded to true so this doesn't happen again.
TablesAlreadyAdded=true;


protected void button2_Click(object sender, System.EventArgs e)

BindingManagerBase bmGrid;
bmGrid = BindingContext[myDataSet, "Customers"];
MessageBox.Show("Current BindingManager Position: " + bmGrid.Position);


private void Grid_MouseUp(object sender, MouseEventArgs e)

// Create a HitTestInfo object using the HitTest method.

// Get the DataGrid by casting sender.
DataGrid myGrid = (DataGrid)sender;
DataGrid.HitTestInfo myHitInfo = myGrid.HitTest(e.X, e.Y);
Console.WriteLine(myHitInfo);
Console.WriteLine(myHitInfo.Type);
Console.WriteLine(myHitInfo.Row);
Console.WriteLine(myHitInfo.Column);


// Create a DataSet with two tables and populate it.
private void MakeDataSet()

// C

将DataTable数据绑定到DataGrid - 代码背后

我创建了DataGrid并且我不想添加DataTemplateColumns泛型,所以它取决于我作为源放置的Data表的列数!但是当我完成所有这些并将DataGrid列绑定到DataTable列时,我的情况是我在DataGrid中获得了正确的行数,但它只是来自第一行的数据。那么,我做错了什么?

这是代码:

Binding binding = new Binding();
binding.Path = new 
PropertyPath(dataTable.Columns[i].ColumnName.ToString());
binding.Source = dataTable

FrameworkElementFactory textBlock = new 
FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.TextProperty, binding);

DataTemplate dataTemplate = new DataTemplate();
dataTemplate.VisualTree = textBlock;
dataGridTemplateColumn.CellTemplate = dataTemplate;
dgTab1.Columns.Add(dataGridTemplateColumn);

我认为我有绑定问题,但我不知道如何解决它,显然!

答案

使用SetBinding(而不是SetValue)方法绑定到Text属性:

FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetBinding(TextBlock.TextProperty, binding);

以上是关于datagrid数据绑定的概念的主要内容,如果未能解决你的问题,请参考以下文章

easyui datagrid 数据绑定 java

easyui的datagrid怎么绑定数据库

通过 ActionScript 将数据绑定到 DataGrid

在XAML代码中绑定数据时,WPF DataGrid ItemsSource绑定不显示数据

如何将Array数据绑定到DataGrid并实现数据更新?

怎么把数据库中的数据通过jquery easyui datagrid进行绑定绑定