[英]How to assign a value to a cell of DataGridView?
我正在嘗試設置第二個值的單元格DataGridView
的,特別是作為happean ComboBox
類的數據綁定,例如:
myComboBox.DisplayMember = "NAME"
myComboBox.ValueMember = "id_value"
您如何看到我顯示了名稱,但是當我執行myComboBox.SelectedValue
我獲得了所選值的ID。 我想知道如何在DataGridView上實現相同的目標。 實際上,我只能添加這樣的值:
myDataGrid.Rows.Add({"TEST"})
如上例所示,如何為行添加值?
一種可能是將數據加載到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.