一種可能性是將數據加載到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」事件。 –