Displaying database record on a label in VB.Net - mysql

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

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")

Related

MS Access Pass Form Through Function

I am trying to create a function that will allow me to use various command buttons without having to recreate the code every time.
To do this I have to pass the form name through a function
Function:
public Function NewRecord(controlForm, focusForm)
focusForm.SetFocus
DoCmd.GoToRecord , , acNewRecord
controlForm.SetFocus
controlForm - This is the main form akin to the Me function
focusForm - This is for not only the main form but when I create subforms I have to have the focus on the subform to have the command work.
To call the function I did the following:
public sub Command19_Click()
Dim controlForm
Dim focusForm
Set controlForm = Forms![frm_Sales_CustomerProfile]
Set focusForm = Forms![frm_Sales_CustomerProfile]
Call NewRecord(controlForm, focusForm)
End Sub
I get this error that States: Compile Error: Invalid Use Of Property.
You got trapped using an already in this context (the form) used identifier and not using a strong name (NameOfLibrary.NameOfFunction).NewRecordis a forms property, soInvalid Use Of Propertymakes sense. If you useMyModulName.NewRecord(frm1,frm2)everything is fine. If you useNewRecordin Module òr Class it works too as there is no property with same name (I assume;-)).
To be honest, I don't use strong names either (except on database or recordset objects, as I got trapped there too, assuming DAO, using ADODB), but the Pros suggest that and now we know why!
Your function should have just one argument as it is sufficent to pass only the subforms reference if you need that form NewRecord(frm as Access.Form) (note the strong name!). You can easy refer to the mainform with Set mfrm = frm.Parent
Your code;
Public Function FrmNewRecord(frm As Access.Form)
frm.Recordset.AddNew
End Function
Public Sub Command19_Click()
FrmNewRecord(Forms![frm_Sales_CustomerProfile]) ' mainform
FrmNewRecord(Forms![frm_Sales_CustomerProfile]!sfrmControl.Form) ' subform
End Sub
You are passing the same form two times in your code, any reason? If Forms[frm_Sales_CustomerProfile] contains Command19 use Me.
I dropped the .SetFocuspart as not necessary or any reason to for setting focus? Why is NewRecord a function? Doesn't return anything.
btw: I am working on aSubForms(frm)function , that returns a collection of all subforms.
Code:
'SubForms(frm As Access.Form) returns a collection of all subform references in frm
Public Function SubForms(frm As Access.Form) As VBA.Collection
Dim ctr As Access.Control
Dim sfrm As Access.Form
Dim col As New VBA.Collection
For Each ctr In frm.Controls
If ctr.ControlType = acSubform Then
On Error Resume Next
Set sfrm = ctr.Form
If Err.Number = 0 Then
col.Add sfrm, sfrm.Name
End If
On Error GoTo 0
End If
Next ctr
Set SubForms = col
End Function
As a general rule to build say custom menu bars, or ribbons, you can write code that is “form” neutral like this:
Public Function MyDelete(strPrompt As String, strTable As String)
Dim strSql As String
Dim f As Form
Set f = Screen.ActiveForm
If MsgBox("Delete this " & strPrompt & " record?", _
vbQuestion + vbYesNoCancel, "Delete?") = vbYes Then
So note how we don’t need to pass the form name at all – the above code simply picks up the active screen as variable “f”.
At that point you can do anything as if the code was inside the form.
So
Me.Refresh (code inside the form)
Becomes
f.Refresh
So the key concept here is that you don’t need to pass the current active form since screenActive form will enable you to get the current form object anyway.
However, for sub forms and “common” type of code the above falls apart because screen.ActiveForm will return the main form, and not the sub form instance.
So as a second recommended approach, simply always pass the current context form object “me” like this:
Call MySub(me)
And you define your sub like:
Sub MySub(f as form)
Now in this code we can reference "anything" by using "f" in place of "me"
f.Refresh
So just pass “me” if you ever use sub forms. Given the above information, then your code becomes:
public sub Command19_Click()
Call NewRecord(me)
End Sub
And NewReocrd becomes:
Sub NewRecord(f as form)
Now in your newreocrd code, you can use “anything” form the object such as:
f.Name ' get name of the form.
or
City = f.City ' get value of city control
So pass the “whole” form context.
And you could say make a routine to display the City value for any form like:
Call ShowCity(me, "City")
And then
Sub ShowCity(f as form, strControlToShow as string)
Msgbox "City value = " & f(strControlToShow)
So OFTEN one will write code that works for any form by simply picking up the current active form as:
Dim f As Form
Set f = Screen.ActiveForm
And note how the above code picks up right away the active form – this is a good idea since then if focus changes, the “f” reference will remain intact for the code that follows in that “general” routine that is called + used from many forms.
However due to the sub form issue, then often it simply better to always pass the “whole” forms instance/object with:
Call MyNewRecord(me)
And then define the sub as:
Sub MyNewReocord(f as form)
DoCmd.GoToRecord acDataForm, f.Name, acNewRec
End Sub
And you could optional add “focus” to above with
f.SetFocus
So for a lot of menu or ribbon code, you don't pass the form object, but simply use screen.ActiveForm, and you can also use Screen.ActiveControl (again great for menu bar or ribbon code to grab what control has focus). However due to sub form limitations, then often passing "me" to the routine will achieve similar results if not better in some cases.

How to control combo box values in vb.net 2010

Hello to all I am new here and also new to VB.NET. I want to control my combo box values to show all names from MySQL database. When I select name from combo box, I want to set the textbox text.
Private Sub fnames()
Try
Dim reader As MySqlDataReader
dbcon.Open()
Dim kweri2 As String = "select * from customer order by lname"
mysqlcmd = New MySqlCommand(kweri2, dbcon)
reader = mysqlcmd.ExecuteReader
While reader.Read
search_cmb.Items.Add(reader.GetString("lname"))
search_cmb.ValueMember = reader.GetString("customer_id")
End While
dbcon.Close()
Catch ex As Exception
MsgBox("Error: " & ex.Message)
Finally
dbcon.Dispose()
End Try
End Sub
then i called the fname() function on load and then:
Private Sub search_cmb_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles search_cmb.SelectedIndexChanged
costumerid_txt.Text = search_cmb.ValueMember.ToString()
End Sub
This code, however, does not work properly. It only shows all lnames but when I select one it will set the string "2" on the textbox which is 2nd id from database and it is not changing even when I choose a different option in the combo box.
Any help would be appreciated.
You are completely misusing the ValueMember property. The ValueMember is the member from which the value is drawn, not the value itself. It is only relevant when using data-binding, so use data-binding. You bind a list of items to the control, set the DisplayMember to the name of column/property from which to draw the text to be displayed and set the ValueMember to the name of the column/property from which to draw the corresponding value.
Don't use a data reader but rather a data adapter. Call Fill on it to populate a DataTable and then bind that to the control:
search_cmb.DisplayMember = "lname"
search_cmb.ValueMember = "customer_id"
search_cmb.DataSource = myDataTable
When the user makes a selection, you then get the value for the selected item from the SelectedValue property:
costumerid_txt.Text = search_cmb.SelectedValue.ToString()
That said, you don't need any code to transfer data from the ComboBox to the TextBox. Just bind the TextBox to the same DataTable and it will happen automatically:
search_cmb.DisplayMember = "lname"
search_cmb.DataSource = myDataTable
costumerid_txt.DataBindings.Add("Text", myDataTable, "customer_id")
I'd probably also recommend binding the DataTable to a BindingSource first and then binding that to the controls if you intend to make changes and save them.

Populate a textbox with mysql data after a combobox selection

So I have 2 mysql tables, one called "Service_Details" and one called "Payment_details"
I have a combobox in my form which displays the "service_id" field from the service table.
I'm trying to code a textbox, so when I select the service id from the combobox it writes the "service" which is another field in my service details table. The service id is linked to a service.
I am getting errors 'identifier expected' at [0] and 'Value of type 'system.data.datatablecollection' cannot be converted to 'string' at dss.tables
I can't seem to get it working after browsing the internet for an hour
Here is my code:
Private Sub cbxserviceid_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxserviceid.SelectedIndexChanged
Dim dss As New DataSet
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID='" + cbxserviceid.Text + "'", objconnection)
Dim cmddd = New MySqlCommandBuilder(daa)
daa.Fill(dss)
txtService1.Text = dss.Tables[0].Rows[0]["Service"].ToString();
End Sub
The indexes in VB.NET are expressed using the round braces, the square brackets are used in C#
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
Also avoid to use string concatenation for sql command texts, use always a parameterized query
Private Sub cbxserviceid_SelectedIndexChanged(......)
Dim dss As New DataSet
if cbxserviceid.SelectedIndex <> -1 Then
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID=#id", _
objconnection)
daa.SelectCommand.Parameters.AddWithValue("#id", Convert.ToInt32(cbxserviceid.Text))
daa.Fill(dss)
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
End If
End Sub
I have also removed the creation of the MySqlCommandBuilder, being the adapter a local variable it has no sense or effect (if this is all your code in this event of course).
Looking at the comments below and the chat with the poster there is also another error to fix.
When assign a DataSource, DisplayMember and ValueMember property of a combobox it is mandatory to follow a precise order to avoid unwanted side effects
cbxserviceid.DisplayMember = "ServiceID"
cbxserviceid.ValueMember = "ServiceID"
cbxserviceid.DataSource = datatable

LINQ to SQL datagridview query returns length, not value

I've got a Windows Form with a button and a datagridview. The project includes a working database connection and LINQ to SQL class. I'm trying to bind the datagridview to the LINQ to SQL.
In a code module I've got this:
Public Function DataGridList() As BindingSource
Dim NewBindingSource As New BindingSource()
Dim db As New DataClasses1DataContext()
NewBindingSource.DataSource = _
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
Return NewBindingSource
End Function
And this button_click code in the form:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = DataGridList()
End Sub
When I click the button I get the length of the school names in the datagridview, with a column header of "length."
If I just run this very similar code in the button_click instead, the school names appear correctly in the immediate window:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim db As New DataClasses1DataContext()
Dim TestQuery =
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
For Each block In TestQuery
Debug.Print(block)
Next
End Sub
Give this a try:
Public Function DataGridList() As BindingSource
Dim NewBindingSource As New BindingSource()
Dim db As New DataClasses1DataContext()
NewBindingSource.DataSource = _
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select New With { Key .Value = Block.gr6_school } Distinct
Return NewBindingSource
End Function
This should give it a property that the DataGridView can pick up on. The New With... creates an anonymous object with a Property named Value. The DataGridView works on this type of object by enumerating the public properties and rendering them as columns. If you had needed more than one value, you could have added additional items inside the curly braces in the same way separated by commas. See Anonymous Types (Visual Basic) for more information.
You might try adding a .ToString to the Select:
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school.ToString Distinct
I believe that Debug.Print does an implicit conversion to .ToString when it prints to the immediate window. However, a datagrid cell treats everything as an object and displays the default property for that object.
Turns out, of course, this has been addressed often, including on SO, and here. The route I chose was to use an intermediate DataTable:
Public Function DataGridList() As DataTable
Dim NewDataTable As New DataTable
Dim db As New DataClasses1DataContext()
Dim i As Int32
Dim qry =
From Block In db.BLOCK_ASSIGNMENTs.AsEnumerable
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
NewDataTable.Columns.Add("School")
For i = 0 To qry.Count - 1
NewDataTable.Rows.Add(qry(i))
Next
Return NewDataTable
End Function
This seems pretty slow the first time it runs, so I may try something else in the future, but it allows me to feed the grid via LINQ, which is what I want to work with.
(I would like to use the qry's CopyToDataTable property, but it's only available if the query returns a DataTableRows collection, or some such, and my hacking around didn't reveal how to do that.)

Referencing global variable - MS Access

Im trying to pass the name of a global variable to a sub routine and would like to know how to reference it. For example I could do the below with a control:
Private Sub passCtrlName(ctlName as String)
Me.Controls(ctlName) = "Whatever"
End Sub
Edit:
For Example
Public imGlobVar As String
Public Sub passGlobVar(frm as Form, ctlName as String, globVar as String)
frm.Controls(ctlName) = globVar
End sub
And call it as
Private Sub imaButton_Click()
imGlobVar = "something"
Call passGlobVar(Me , txtBox1, imGlobVar)
End sub
2nd Edit:
It seems that I could most definitely be barking up the wrong tree here, so I will explain what I'm trying to achieve.
I have a form that has textboxes for the users (risk) address, with a checkbox at the top that lets the user select that this address is the same as the 'contact' details already on the system, and the textboxes are locked.
Populating the textboxes is fine and works. What I use the global variables for is to improve usability (albeit slightly).
The user can add new details, and if they hit the checkbox 'make same as contact' the details that they have entered are stored in the global variables, one for each control.
If the user has made a mistake by hitting the checkbox, they haven't lost these value, and by unchecking the box the entered values are returned.
I hoped to create a sub routine where I could pass the name of the global variable and control and calling this routine, as opposed to writing it out for each control.
I have a feeling that I could be using the wrong technique to achieve my goals. But in answer to my original question, it appears that you can not pass global variables to sub routines in the manner that I wished.
You do not need to pass global variables, you can simply refer to them by name. Note that global variables are reset if an unhandled error occurs.
In http://msdn.microsoft.com/en-us/library/dd897495(office.12).aspx you will find a section on Scope and Lifetime of Variables and Constants.
In a module:
Option Explicit
Public glbVarName As String
Const MyConstant=123
Sub InitVar
glbVarName="Something"
End Sub
Any other module, includeing a form's class module:
Sub SomeSub
MsgBox glbVarName
SomeVar=2+MyConstant
End Sub
If you're asking if you can dynamically reference global variables using a string containing the variable name the answer is no. You could use a single global array and pass the index, which would allow you to dynamically reference an element of the array.
[Edit]
In response to the clarification in the question: You could just save the value of each control to its Tag property when the user checks the checkbox. Then, if the user unchecks the checkbox, you can just loop over your controls and assign the value from the Tag back to the Value of the control.
You could store the values from your controls in a Dictionary object, using the control names as the dictionary keys. Then you can retrieve the value for each control based on the control's name.
Option Compare Database
Option Explicit
Const cstrMyControls As String = "Text0,Text2,Text4,Text6"
Dim objDict As Object
Private Sub chkToggle_Click()
If Me.chkToggle = True Then
Call SaveValues
Else
Call RestoreValues
End If
End Sub
Private Sub SaveValues()
Dim varControls As Variant
Dim i As Long
Set objDict = Nothing 'discard previous saved values '
Set objDict = CreateObject("Scripting.Dictionary")
varControls = Split(cstrMyControls, ",")
For i = 0 To UBound(varControls)
objDict.Add varControls(i), Me.Controls(varControls(i)).Value
Next i
End Sub
Private Sub RestoreValues()
Dim varControls As Variant
Dim i As Long
If objDict Is Nothing Then
'MsgBox "No values to restore." '
Else
varControls = objDict.keys()
For i = 0 To UBound(varControls)
Me.Controls(varControls(i)).Value = objDict(varControls(i))
Next i
End If
End Sub
I use additional field in table - name cancel - of course boolean - when i'm not sure if contents of fields will be valid I set it true. If this field will be true by the end - then I clean up (it may be all record or some fileds of course). Very easy.