Populate form textbox by sql database

jon2371

New member
Joined
Jul 6, 2009
Messages
1
Programming Experience
Beginner
Hi Experts,

Please help me on this, On Form Load i have to populate the 1st record on sql table to textboxes & combobox.

This my syntax, kindly check.
-----------------------------------------------------------------------------------------------------------
Public Class frmMachine
    Dim cn As New SqlConnection("Data Source=SERVERHP;Initial Catalog=ProdSystem-Mega;User ID=sa;Password=p@ssw0rd")
    Dim cmd As New SqlCommand

    Private Sub frmMachine_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim mySelectQuery As String = "Select machcode,machname,machtype,machlocation,brand,status from tblmachine"
        cn.Open()
        txtmachcode.Text=@machcode
        cn.Close()
    End Sub

    Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
        If txtmachcode.Text = "" Then
            MessageBox.Show("Machine Code is empty. This is a required field.", "Error Message")
        ElseIf txtmachname.Text = "" Then
            MessageBox.Show("Machine Name is empty. This is a required field.", "Error Message")
        ElseIf cbomachtype.Text = "" Then
            MessageBox.Show("Machine Type is empty. This is a required field.", "Error Message")
        ElseIf cbolocation.Text = "" Then
            MessageBox.Show("Location is empty. This is a required field.", "Error Message")
        ElseIf cbobrand.Text = "" Then
            MessageBox.Show("Brand is empty. This is a required field.", "Error Message")
        ElseIf cbostatus.Text = "" Then
            MessageBox.Show("Status is empty. This is a required field.", "Error Message")
        Else
            Try
                cn.Open()
                cmd.Connection = cn
                cmd.CommandText = "INSERT INTO tblmachine(machcode,machname,machtype,machlocation,brand,status) VALUES('" & txtmachcode.Text & "','" & txtmachname.Text & "','" & cbomachtype.Text & "','" & cbolocation.Text & "','" & cbobrand.Text & "','" & cbostatus.Text & "')"
                cmd.ExecuteNonQuery()
                cn.Close()
            Catch ex As Exception
                MsgBox("Can not open SQL Connection ! ")
            End Try
        End If
    End Sub
End Class 



Thanks,
Jon
 
If you are going to retrieve only one data, use this select query

Select top 1 machcode,machname from tblsample order by id asc
Put this query inside your command and set datareader.
while mydatareader.read = true then
txtbox.text = dr(0)
cbobox.text = dr(1)
end while
 
Back
Top