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

时间:2015-02-05 13:21:28

标签: vb.net textbox dataset

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

数据集包含2个表。 Environments表有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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

如果要将Control绑定到数据源的特定元素(而不是整个集合),可以使用BindingSource并将其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()

结果:

enter image description here

相关问题