如何为DataGridView的单元格赋值?

时间:2016-01-06 12:37:58

标签: vb.net

我试图将第二个值设置为DataGridView的单元格,特别是在ComboBox中像DataBinding一样,例如:

myComboBox.DisplayMember = "NAME"
myComboBox.ValueMember = "id_value"

你怎么看我显示的名字,但当我myComboBox.SelectedValue时,我得到了值的id。我想知道如何在DataGridView上实现相同的功能。实际上我只能添加这样的值:

 myDataGrid.Rows.Add({"TEST"})

我如何为行添加一个值,如上例所示?

1 个答案:

答案 0 :(得分:1)

一种可能性是将数据加载到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