将数据集绑定到循环中动态生成的文本框

Binding dataset to dynamic generated textbox in loop

我无法让动态生成的文本框在将其绑定到数据集时显示正确的数据。

数据集包含 2 tables。 Environments table 有 4 行,值为 DEVTSTACCPROD.

Dim cma As CurrencyManager
cma = CType(BindingContext(oConfData.dsJimConfig.Tables("Environments")), CurrencyManager)

For i As Integer = 0 To intNrEnvCombi - 1
   cma.Position = i

   Dim txt As TextBox = New TextBox
   With txt
      .Margin = New Padding(5)
      .TabIndex = intTabIdx
      .Name = arrLabelText(3) & i
         If i > cma.Count - 1 Then
          .Text = ""
        Else
          .DataBindings.Add(New Binding("Text", oConfData.dsJimConfig.Tables("Environments"), "Environment"))
        End If
      .CausesValidation = True
    AddHandler txt.Validating, AddressOf Text_Validating
    AddHandler txt.GotFocus, AddressOf Text_setClear
    AddHandler txt.Leave, AddressOf Text_Format
  End With
Next

在所有文本框中,显示最后一条记录的数据PROD

我哪里做错了?

如果要将 Control 绑定到数据源的特定元素(而不是整个集合),可以使用 BindingSource and set its Position property 到元素的索引想绑定到。


考虑这个简单的例子:

Dim table = New DataTable()
table.Columns.Add("FooBar")
table.Rows.Add({"First"})
table.Rows.Add({"Second"})
table.Rows.Add({"Third"})

Dim panel = new FlowLayoutPanel()
For i = 0 To 2 
    Dim bs = new BindingSource With
    {
        .DataSource = table,
        .Position = i
    }

    Dim box = new TextBox
    box.DataBindings.Add(New Binding("Text", bs, "FooBar"))
    panel.Controls.Add(box)
Next

Dim f = new Form()
panel.Dock = DockStyle.Fill
f.Controls.Add(panel)
f.ShowDialog()

结果: