Question Doubt about BindingSource and variable

pabletoreto

New member
Joined
Jul 27, 2011
Messages
1
Programming Experience
1-3
How can I pass value from bindingsource (current record and column "xxx") to a variable?

So, sorry for my english it must be the worst ever, I know you guys are very busy people but please try to help me.
I'm coding a VB 2010 form and get the info from a SQL Xpress 2008 database and show the info in textbox, I'm working with a BindinSourse and a BindingNavigator and If a run the project all controls are syncronized with the data. It means the bindingsource pass the data to the textbox controls in such a way that when I press the arrow in the BindingNavigator it moves forward and the info goes to the due textbox, so far I have done this:

Public Function ListarDatos() As DataTable
Dim sql As String = "SELECT * FROM registro"
Dim da As New SqlDataAdapter(sql, cnn)
Dim dt As New DataTable("registro")
da.Fill(dt)
Return dt
End Function

Private Sub empezar()
bs.DataSource = ListarDatos()
BindingNavigator1.BindingSource = bs
DataGridView1.DataSource = bs
codigotext.DataBindings.Add("Text", bs, "codigo") 'and more textbox...
Label1.Text = String.Format("Empleados registrados: {0}", DataGridView1.Rows.Count)
cnn.Close()

what I want is to save the value of codigo into a variable called cod in order to show this value through a label like this:
dim cod as string
codigotext.DataBindings.Add("Text", bs, "codigo")
cod = Me.codigotext.Text
label3.text=cod

but it doesn´t work because I only get the very first data and when I move forward through the BindingNavigator the label doesn´t show the due information, recently I got a solution but it´s such a dumyy code, what I did is to mimic that behavior using the codigotext_TextChanged event, like this:

Private Sub codigotext_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles codigotext.TextChanged
Dim cod As String
cod = Me.codigotext.Text
Label3.Text = cod
End Sub

could you guys help me please?
 
Last edited:
When the user makes a selection, you get the corresponding item from the BindingSource using its Current property. That property is type Object because any type of objects can be bound to the BindingSource. It's up to you to cast that object as the appropriate type. In your case, because you have bound a DataTable, the items will be type DataRowView.
Dim selectedRow = DirectCast(myBindingSource.Current, DataRowView)
You can pretty much treat a DataRowView in the same way as you do a DataRow, which means that you can get a field value from it by column name or index.

That said, the whole point of the BindingSource is the binding. Unless you only want the Label to show the current value under certain circumstances, you should simply bind the label to the BindingSource too. That way, whenever the user selects a row in the grid, the appropriate column of the selected row will automatically be displayed in the Label.
 
Back
Top