一种可能性是将数据加载到DataTable中,添加BindingSource,将BindingSource的数据源设置为DataTable,然后使用BindingSource作为DataGridView的数据源。
从这里我们不能显示一个或多个列,隐藏列的使用方式与ComboBox DisplayMember和ValueMember一样。下面的例子是一个简单的演示,可以让你试试这个。请注意,从逐行加载DataGridView到下面建议的方法几乎没有开销。
我特意让事情变得简单,所有代码都依赖于Framework 3.5或更高版本,如果使用早于版本的行,则需要将行连续字符或将行移动到一行。
''' <summary>
''' Requires 1 DataGridView, 1 TextBox, 2 Buttons
''' </summary>
''' <remarks></remarks>
Public Class Form1
Private bs As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
bs.DataSource = MimicLoadingData()
DataGridView1.DataSource = bs
End Sub
''' <summary>
''' Mimic loading data from a data source be it
''' a text file, excel or database etc.
''' </summary>
''' <returns></returns>
''' <remarks>
''' Set ColumnMapping to Hidden so they are
''' not shown in the DataGridView
''' </remarks>
Private Function MimicLoadingData() As DataTable
Dim dt As New DataTable
dt.Columns.Add(New DataColumn With
{
.ColumnName = "ID",
.AutoIncrement = True,
.DataType = GetType(Integer),
.ColumnMapping = MappingType.Hidden
}
)
dt.Columns.Add(New DataColumn With
{
.ColumnName = "Name",
.DataType = GetType(String)
}
)
dt.Columns.Add(New DataColumn With
{
.ColumnName = "IdName",
.DataType = GetType(Integer),
.ColumnMapping = MappingType.Hidden
}
)
dt.Rows.Add(New Object() {Nothing, "Karen", 34})
dt.Rows.Add(New Object() {Nothing, "Bob", 100})
dt.Rows.Add(New Object() {Nothing, "Anne", 50})
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If bs.Current IsNot Nothing Then
MessageBox.Show(
CType(bs.Current, DataRowView).Row.Field(Of Integer)("IdName").ToString)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If bs.Current IsNot Nothing Then
Dim value As Integer = 0
If Integer.TryParse(TextBox1.Text, value) Then
CType(bs.Current, DataRowView).Row.SetField(Of Integer)("IdName", value)
End If
End If
End Sub
End Class
什么是行(2)? –
这是一个内容,现在我换成 –
这仅仅是为了打印目的吗?在这种情况下,请查看可以显示任何格式的“CellFormatting”事件。 –