2016-01-06 66 views
0

我正在尝试设置第二个值的DataGridView细胞,特别是在ComboBox像数据绑定happean,例如:如何将值分配给DataGridView的单元格?

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

你怎么能看到我已经显示的名称,但是当我做myComboBox.SelectedValue我得到了选定的值的ID。我想知道如何在DataGridView上实现同样的功能。其实我只能够加入这样一个值:

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

我怎么可以分配到该行新增了值在上面的例子?

+0

什么是行(2)? –

+0

这是一个内容,现在我换成 –

+0

这仅仅是为了打印目的吗?在这种情况下,请查看可以显示任何格式的“CellFormatting”事件。 –

回答

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 
+0

有趣的解决方案,但艰难的解决方法 –

+0

我不会称之为硬解决方案,因为没有别的工作可以丢失值,而DataRow的标签属性不会失去价值。带有BindingSource或BindingList的列表(T)可以被使用,但是这可能会导致与其他事情有关的不当问题。底线总是最好用数据源而不是单元格。 –

相关问题