绑定到表时,Datagridview的列数错误

时间:2011-11-04 18:50:03

标签: vb.net datagridview

我需要在单元格中有多行,所以我使用DataGridViewTextBoxColumn.DefaultCellStyle.WrapMode = DataGridViewTriState.True。 我在设计器中添加了列(datagridviewtextboxcolumn)。然后将datagridview绑定到一个与datagridview具有完全相同列的表。然后我发现datagridview有重复的列:第一列是空的(我猜是通过设计器添加),第二列是来自表的数据。我的问题是如何正确地允许多行并同时绑定到表?

在设计师中

Friend WithEvents DGV As New System.Windows.Forms.DataGridView
Friend WithEvents columnClient As System.Windows.Forms.DataGridViewTextBoxColumn
Friend WithEvents columnAccount As System.Windows.Forms.DataGridViewTextBoxColumn
Me.DGV.Columns.AddRange(New System.Windows.Forms.DataGridViewColumn() {Me.columnClient, Me.columnAccount})
Dim cellStyle As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle
cellStyle.WrapMode = DataGridViewTriState.True
Me.columnClient.DefaultCellStyle = cellStyle
Me.columnAccount.DefaultCellStyle = cellStyle

然后我将datagridview绑定到表

DGV.DataSource = m_table
m_table.Columns.Add(columnClient)
m_table.Columns.Add(columnAccount)

Dim rowText As DataRow = m_table.NewRow
Dim strBaseKey As String="base key"
Dim accountkey As String="account key"
rowText(columnClient) = strBaseKey
rowText(columnAccount) = accountKey

添加:我刚刚删除了设计器中的列,现在可以正常工作了。

1 个答案:

答案 0 :(得分:0)

解决方案很简单:只是不要在设计器中向datagridview添加列;而是将列添加到表中,然后将datagridview绑定到表。要在datagridview中启用多行,请设置column.DefaultCellStyle.WrapMode = DataGridViewTriState.True

DGV.DataSource = m_table 
m_table.Columns.Add(columnClient) 
m_table.Columns.Add(columnText) 

Dim rowText As DataRow = m_table.NewRow 
rowText(columnClient) = "Bob"
rowText(columnAccount) ="Account1" & Encironment.Newline & "Account 2"

DGVTable.Columns(columnText).DefaultCellStyle.WrapMode = DataGridViewTriState.True

datagridview将显示:

   columnClient     columnAccount
   Bob              Account1
                    Account2