vb.net使用在运行时添加的多个控件

时间:2012-09-21 21:07:28

标签: vb.net controls runtime naming

我正在为数据表中的每条记录的Tab Control添加一个标签页和datagridview。

我想为每条记录创建一个新的Tab / DataGridView(现在会有~3)。我正在声明一个新的DataGridView D.我如何在以后引用这些控件?

我想做的事情就是将datagridview中的更改保存到数据库中。目前我可以在屏幕上获取数据,看起来不错,但我相信我没有正确添加DataGridView控件,因为我一直在重复使用“D”作为控件。

            Dim dt As New DataTable

        GetDataTable("SELECT * FROM aFeeTypes DescSeq", dt)

        Dim i As Integer

        'for each class in the datatable add a tab and a datagridview
        For i = 0 To dt.Rows.Count - 1

            Dim dr As DataRow
            dr = dt.Rows(i)

            Dim D = New DataGridView
            D.Visible = True

            Dim tp As New TabPage
            tp.Name = "tp" & i
            tp.Text = dr.Item("Desc2")
            frmUI.tcFee.TabPages.Add(tp)
            frmUI.tcFee.TabPages(i).Controls.Add(D)

            dgv_Fill(D, "SELECT * FROM Fee WHERE ClassID=" & dr.Item("ClassID") & " ORDER BY Seq")

            D.AutoResizeColumns()
            D.Width = tp.Width
            D.Height = tp.Height

        Next i

这不起作用:

            With frmUI.Controls("D" & i)
                .AutoResizeColumns()
                .Width = tp.Width
                .Height = tp.Height
            End With

2 个答案:

答案 0 :(得分:1)

D纯粹是您使用它的范围中的变量名。

您需要为控件提供一个唯一的Name,以便稍后可以引用它。

  

可以在运行时使用Name属性来评估对象   名称而不是类型和程序名称。因为Name属性   返回一个String类型,它可以用case-style逻辑来计算   语句(在Visual Basic中选择语句,在。中切换语句   Visual C#和Visual C ++)。

答案 1 :(得分:0)

我找到了问题的解决方案。问题是新行具有自动编号ID。

当da.update(dt)发生时,新行将插入数据库。数据库知道新的自动编号ID。但是,数据表没有。

要获知数据表,需要重新填充数据适配器。但是,这会导致数据表包含所有旧行以及所有新行,并且它们都出现在datagridview中。

通过清除数据表中的旧行,填充将刷新数据表中的所有数据,从而刷新datagridview。

    Public Sub dgv_AddRow(ByVal dgvName As String)

    Dim dgv As DataGridView = colDataGridView.Item(dgvName)

    Dim da As SqlDataAdapter = colDataAdapter.Item(dgvName)
    Dim dr As DataRow = frmUI.allDataSet.Tables(dgvName).NewRow

    'autopopulate the class id
    dr("ClassID") = dgv.Parent.Tag

    'add the new row
    frmUI.allDataSet.Tables(dgvName).Rows.Add(dr)

    'get the changed table
    Dim dt As DataTable = frmUI.allDataSet.Tables(dgvName)

    'inserts the new row to the database.  concurrency violation 
    'will occur because datatable does not know the new Autonumber ID for the new row.

    da.Update(dt)

    'remove the datatable rows so they can be replaced using the adapter fill
    'if rows are not cleared, following fill causes datatable to 
    'have existing rows plus all the rows again due to the fill

    frmUI.allDataSet.Tables(dgvName).Rows.Clear()

    'refill the adapter (refill the table)
    'Everything you do to the underlying dataTable
    'gets displayed instantly on the datagridview

    da.Fill(frmUI.allDataSet, dgvName)



End Sub