Displaying database record on a label in VB.Net

Issue

I have this problem that when I put id no. in the textbox1 and click the button1 the record successfully shows, but when I change the id no. in the textbox1 and click button1 again the error says

ArgumentException was unhandled

This causes two bindings in the collection to bind to the same property. Parameter name: binding

I really don’t understand the meaning of this, by the way still new and getting used to vb.net

Imports MySql.Data.MySqlClient

Public Class Form16

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim thisConnection As New MySqlConnection("server=localhost;user id=root;database=db")
        Dim DataSet1 As New DataSet


        Dim sql As String = "SELECT * FROM voter where vid='" & TextBox1.Text & "'"
        Dim da As New MySqlDataAdapter(sql, thisConnection)

        da.Fill(DataSet1, "db")
        Label2.DataBindings.Add("text", DataSet1, "db.fname")
        Label10.DataBindings.Add("text", DataSet1, "db.mi")
        Label11.DataBindings.Add("text", DataSet1, "db.lname")
        Label12.DataBindings.Add("text", DataSet1, "db.yr")
        Label13.DataBindings.Add("text", DataSet1, "db.sec")
        Label14.DataBindings.Add("text", DataSet1, "db.vstatus")

    End Sub
End Class

Solution

If you don’t clear the DataBindings collection before rebinding, this error will be thrown because a control can only have one binding to a specified property.

For instance, Label2 can only have one binding to the property Text. But when you’re clicking the button for the second time the binding added in the first click is still in the collection.

First click:

Label2.DataBindings.Add("Text", DataSet1, "db.fname")

Second click:

'Will throw an error because there's already a binding to property `Text`:
Label2.DataBindings.Add("Text", DataSet1, "db.fname")

Before you add a new binding, be sure the binding doesn’t already exists.

'Always do a reversed loop when removing items from a collection.
For index As Integer = (Label2.DataBindings.Count - 1) To 0 Step -1
    If (Label2.DataBindings.Item(index).PropertyName = "Text") Then
        'Ops, a binding to the property `Text` already exists.
        'Remove this and we'll be fine.
        Label2.DataBindings.RemoveAt(index)
    End If
Next

'We can now safely add a new binding to the `Text` property.
Label2.DataBindings.Add("Text", DataSet1, "db.fname")

A more simpler way is to just clear the collection.

Label2.DataBindings.Clear()
Label2.DataBindings.Add("Text", DataSet1, "db.fname")

Answered By – Bjørn-Roger Kringsjå

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published