#VB.NET“Datagridview.datasource = datatable”不会将数据表中的列添加到网格中

时间:2015-07-19 07:27:28

标签: vb.net datagridview datatable

我有一个处理datagridview的类属性,如下所示:

Public Shared Property DetailGrid() As System.Windows.Forms.DataGridView
    Get
        Return _DetailGrid
    End Get
    Set(ByVal value As System.Windows.Forms.DataGridView)
        _DetailGrid = value
    End Set
End Property

现在我在类构造函数中将此dataridview实例化为:

  Public Sub New()
    _DetailGrid = New System.Windows.Forms.DataGridView
End Sub

我在winform上填充了这个“DetailGrid”datagridview。在Winform上,首先我创建包含“DetailGrid”属性的上述类的对象,然后尝试填充此“Detail Grid”,如下所示。

Private Sub PopulateDetailGrid()
    Dim TextBoxCell As DataGridViewTextBoxCell
    Dim dc_Category As DataGridViewComboBoxColumn
    Dim dc_Notes As DataGridViewComboBoxColumn
    Dim strSQL As String = ""

    Try
        DetailGrid.DataSource = Nothing
        StrClosedYrs = BuildClosedYrsStr()
        'SearchStr = IIf(InStr(txtSearchText, "Multiple Searches Seperated By Comma") > 0, "", Trim(txtSearchText))
        dc_Category = GetComboBoxColumn_Category()
        dc_Notes = GetComboBoxColumn_Notes()
        DetailGrid.Columns.Add(dc_Category)
        DetailGrid.Columns.Add(dc_Notes)

        Using Connection = GetConnection()
            dt = New DataTable
            strSQL = "SELECT * FROM dbo.Fn_GetData(CONVERT(DATETIME,'" & dtpFrom & "',105), CONVERT(DATETIME,'" & dtpTo & "',105), '" & Categories & "', '" & SearchStr & "')"
            da = New SqlDataAdapter(strSQL, Connection)
            da.Fill(dt)
            da.Dispose()
        End Using

        DetailGrid.DataSource = dt
        DetailGrid.AutoResizeColumns()
        DetailGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
        DetailGrid.AllowUserToAddRows = False

        DetailGrid.Columns("hKey").Visible = False

。 。 。     结束子

在上面的代码中,当我说“DetailGrid.Datasource = dt”时,代码不显示任何错误,但当我去查看“DetailGrid”的列数时,它只显示我手动添加的两列上面提到的“PopulateDetailGrid”函数。

然后在DetailGrid.Columns(“hKey”)行上抛出错误。可见  =假。

实际上,列“hkey”是绑定到DetailGrid的数据表的一部分。

我不知道为什么这表现得很奇怪。请帮帮我。

0 个答案:

没有答案