public variables on load (vb.net) - vb.net

i defined some public variables in a class, when calling some variables in another class it works sometimes and sometimes not, the below code it works for the textbox but not in the form load, what i need is to run some sql sps to retrieve some data
Imports PZ_Project.DBConnClass
Imports System.Data.SqlClient
Imports System.Data
Public Class Main
Private Sub Main_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim UserTypeID As String = DBConnClass.LogedinUserType
MainMenu.Items.Add("Hi1")
Dim UserMainMenu As New SqlCommand("User_Menu_Items_App")
UserMainMenu.CommandType = CommandType.StoredProcedure
UserMainMenu.CommandText = "User_Menu_Items_App"
UserMainMenu.Connection = Conn
Dim UserTypeParam As SqlParameter = UserMainMenu.Parameters.Add("#intUserTypeID", LogedinUserType)
Dim SQLUserTypeTableAdaptor As SqlDataAdapter = New SqlDataAdapter(UserMainMenu)
Dim SQLUserTypeDataSet As DataSet = New DataSet()
SQLUserTypeTableAdaptor.Fill(SQLUserTypeDataSet)
MessageBox.Show("1" & UserTypeID)
For i = 0 To SQLUserTypeDataSet.Tables(0).Rows.Count - 1
MessageBox.Show(SQLUserTypeDataSet.Tables(0).Rows(i).Item(0))
MainMenu.Items.Add(SQLUserTypeDataSet.Tables(0).Rows(i).Item(0).ToString)
Next
' Dim obj As Object = UserMainMenu.ExecuteScalar()
'InitializeComponent()
'Dim SelectMenuItems As String
'Dim Menu_Item As String
'Dim tsmi As New ToolStripMenuItem("Users", Nothing)
'MenuStrip1.Items.Add(tsmi)
'SelectMenuItems = "Select Distinct User_Types.Name From Users Inner Join User_Types on User_Types.ID = Users.User_Type_ID Where User_Name = '" + User_Name.Text + "'"
'ConnCommand = New SqlCommand(UserName, Conn)
'Dim SQLUserTypeTableAdaptor As SqlDataAdapter = New SqlDataAdapter(ConnCommand)
'Dim SQLUserTypeDataSet As DataSet = New DataSet()
'SQLUserTypeTableAdaptor.Fill(SQLUserTypeDataSet)
'For i = 0 To SQLUserTypeDataSet.Tables(0).Rows.Count - 1
' UserType.Items.Add(SQLUserTypeDataSet.Tables(0).Rows(i).Item(0).ToString)
'Next
'UserType.Text = UserType.Items(0).ToString
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.MouseEnter
TextBox1.Text = LogedinUserType
MessageBox.Show(LogedinUserName & " / " & LogedinUserTypeName)
End Sub
End Class

Try to change this
Dim UserTypeID As String = DBConnClass.LogedinUserType
to this
Dim DBConnClass As New DBConnClass
Add this
Dim UserTypeID As String= DBConnClass.LogedinUserType

Related

Update Button for Access Database via DataGridView Using OLEDB in VB.NET (Visual Studio 2013)

I have linked an Access database to my program. It populates the DataGridView as it is intended to so that part of the program works. However the new data that i add to my DataGridView wont show up and I don't know what is wrong with my code.
Can anyone see anything wrong or something I've missed out that would cause the code not to function as desired? Thank you in advance :)
Imports System.Data.OleDb
Public Class Form1
Dim j As OleDbConnection
Dim a As OleDbDataAdapter
Dim s As DataSet
Dim lokasidb As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call jaringan()
a = New OleDbDataAdapter("Select * From datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
Private Sub eksekusiSql(ByVal Sql As String)
Dim objcmd As New System.Data.OleDb.OleDbCommand
Call jaringan()
Try
objcmd.Connection = j
objcmd.CommandType = CommandType.Text
objcmd.CommandText = Sql
objcmd.ExecuteNonQuery()
objcmd.Dispose()
MsgBox("The new data successfully saved", vbInformation)
Catch ex As Exception
MsgBox("The new data is failed to save", vbInformation)
End Try
End Sub
Sub jaringan()
lokasidb = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\19106060045_Tugas Modul 5.accdb"
j = New OleDbConnection(lokasidb)
If j.State = ConnectionState.Closed Then j.Open()
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Dim No As String = TextNo.Text
Dim Jenis_Susu_Sapi As String = TextSusu.Text
Dim Jenis_Olahan As String = TextOlahan.Text
Dim Harga_per_kg As String = TextHarga.Text
Dim Tempat_Penjualan As String = TextPasar.Text
Dim Sql_Simpan_Dairy As String = "Insert into datadairy (No, Jenis_Susu_Sapi, Jenis_Olahan, Harga_per_kg, Tempat_Penjualan) values (" + No + ",'" + Jenis_Susu_Sapi + "','" + Jenis_Olahan + "','" + Harga_per_kg + "','" + Tempat_Penjualan + "')"
eksekusiSql(Sql_Simpan_Dairy)
ShowDairydata()
End Sub
Public Sub ShowDairydata()
Call jaringan()
a = New OleDbDataAdapter("Select * from datadairy", j)
s = New DataSet
s.Clear()
a.Fill(s, "datadairy")
DataGridDairy.DataSource = (s.Tables("datadairy"))
End Sub
After adding new data to your database, just use
'DataGridDairy.Databind()'
to refresh.

other type of checkedlistbox need answer

i'm a new guy to learn vb...in my question to save checkedlistbox to database.
my question is:
LocalDatabase table 1: Employee
[EMPLOYEE]
Form1
LocalDatabase table 2 : record
checkedlistbox list form Employee datatable..then i want save the value to database where checkedlistbox selected...i don't know how to coding vb...can somebody help??
i have tried in code by learn in other..but still have in question in checklistbox saving.
my code
vb class
Imports System.Data.SqlClient
Public Class ConnectionDatabase
Public dset As New DataSet
Public adaptor As New SqlDataAdapter
Public conn As New SqlConnection
Public cmd As New SqlCommand
Public locate As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\asus\Documents\vs twins\TT - Copy\TT\twin.mdf';Integrated Security=True"
End class
so in vb coding is:
Imports System.Data
Imports System.Data.SqlClient
Public Class Record
Dim vs As New ConnectionDatabase
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Record_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = vs.locate
dsDIV = New DataSet
daDIV = New SqlDataAdapter("SELECT Name FROM Employee", oCon)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
CheckedListBox1.DataSource = tblDIV
CheckedListBox1.DisplayMember = "Name"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub
Private Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedIndexChanged
Dim TextBox1 As Double
Dim TextBox2 As Double
Dim Ans As Double
WkH = Val(TextBox1.Text)
WkS = Val(TextBox2.Text)
Ans = WkH * WkS
Label4.Text = Ans
End Sub
that is all can be run...but i can't code in the last part (saving into database) can suggest some link or example to learn ??Please Help Thank You..

Populating Textbox and DropdownLists

I am having a hard time trying to populate a textbox, and two dropdown lists. What I am attempting to do is this: when the Company dropdownlist has been selected, it will display a grid of its respective values from a sqldatasource, which it does. Now the next step is once a selection from the company dropdown has been made, a textbox will display the membertype as well as the second dropdownlist. The third dropdown displays the groupid. All these three components have their outputs after a selection has been made. But I cannot seem to get the values to show. I also added code for clarification.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.WebControls
Partial Class companydropdown
Inherits System.Web.UI.Page
Private Sub BindDropDownList(DropdownList1 As DropDownList, query As String, text As String, value As String, defaultText As String)
If Not IsPostBack Then
' Read sql server connection string from web.config file
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
'da.Fill(dt)
End Using
'DropdownList1.DataSource = dt
DropdownList1.DataTextField = "CompanyName"
DropdownList1.DataValueField = "CompanyID"
DropdownList1.DataBind()
'DropdownList1.Items.Insert(0, New ListItem("--Select--"))
End If
End Sub
Protected Sub Member_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList2.DataTextField = "MembershipStatus"
DropDownList2.DataValueField = "MemberTypeID"
' Bind sql server data into the Dropdown List
DropDownList2.DataBind()
Else
DropDownList2.Items.Clear()
End If
End Sub
Protected Sub Group_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex > 0 Then
Dim sConstr As String = ConfigurationManager.ConnectionStrings("ds17701ConnectionString").ConnectionString
Dim Conn As New SqlConnection(sConstr)
Dim dt As New DataTable("tbl")
Using Conn
Conn.Open()
Dim comm As New SqlCommand("SELECT CompanyName,CompanyID FROM CompanyList " + DropDownList1.SelectedValue & " ORDER BY CompanyName", Conn)
Dim da As New SqlDataAdapter(comm)
da.Fill(dt)
End Using
'DropDownList2.DataSource = dt
DropDownList3.DataTextField = "GroupID"
DropDownList3.DataValueField = "GroupID"
' Bind sql server data into the Dropdown List
DropDownList3.DataBind()
Else
DropDownList3.Items.Clear()
End If
End Sub
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
DropDownList2.Enabled = False
'DropDownList3.Items.Clear()
DropDownList3.Items.Insert(0, New ListItem("", "0"))
Dim stateId As Integer = Integer.Parse(DropDownList1.SelectedItem.Value)
If stateId > 0 Then
Dim query As String = String.Format("", stateId)
BindDropDownList(DropDownList1, query, "CompanyName", "CompanyId", "")
DropDownList3.Enabled = True
DropDownList2.Enabled = True
End If
End Sub
End Class

VB.NET & SQL Server database : adding record from textbox

I am trying to make a highscore table that will take the users name from textbox and grab the score from a label on another form and store them into a database called highscores. I can get the connection to work but I can't figure out how to add the records I need added and display them in the datagrid view.
Private MyDatAdp As New SqlDataAdapter
Private MyCmdBld As New SqlCommandBuilder
Private MyDataTbl As New DataTable
Private MyCn As New SqlConnection
Private MyRowPosition As Integer = 0
Private Sub highscore_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MyCn.ConnectionString = "Data Source=(localDB)\v11.0;AttachDbFilename=C:\Users\Scores.mdf;integrated security = true;Connect Timeout = 30"
MyCn.Open()
MyDatAdp = New SqlDataAdapter("Select* from HighScores", MyCn)
MyCmdBld = New SqlCommandBuilder(MyDatAdp)
MyDatAdp.Fill(MyDataTbl)
Dim MyDataRow As DataRow = MyDataTbl.Rows(1)
Dim MyDataRow2 As DataRow = MyDataTbl.Rows(2)
Dim Name As String
Dim Score As String
Name = MyDataRow("Name")
Score = MyDataRow2("Score")
NameBox.Text = Name.ToString
Math.Score.Text = Score.ToString
Me.showRecords()
End Sub
Private Sub showRecords()
If MyDataTbl.Rows.Count = 0 Then
NameBox.Text = ""
Math.Score.Text = ""
Exit Sub
End If
NameBox.Text = MyDataTbl.Rows(MyRowPosition)("Name").ToString
Math.Score.Text = MyDataTbl.Rows(MyRowPosition)("Score").ToString
End Sub
End Class

Code behind for print?

I have a report that I need to print after a sale has completed.
I am having issues with the length and printing when using PrintForm and PrintDocument components however if I right click and select Print from the list the report prints perfectly.
Is there any way that I could write code in my form load event that would imitate the right click print?
Ive been struggling with this part of my project for ages now and the whole thing is now way behind schedule.
My Code for the whole Receipt form page is:
Imports System.Data.OleDb
Imports System.IO
Imports System.Drawing.Printing
Public Class Receipt
Public PicLocation As String
Dim Ctrl1, Ctrl2 As Control
Dim CN As New OleDb.OleDbConnection
Dim CMD As New OleDb.OleDbCommand
Dim DataR As OleDb.OleDbDataReader
'To display into datagrid purpose
Dim dataS As New DataSet
Dim dataAd As New OleDb.OleDbDataAdapter
Public SqlStr, SqlStr1, DBPath, DBStatus, SearchBox As String
Dim X, Y, SqlH, Onh As Integer
Dim SqlUser As String
Dim DataP As Decimal
Dim Balance As Integer
Private Sub Receipt_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'ProductListDataSet' table.
DBPath = (Application.StartupPath & "\ProductList.accdb")
If CN.State = ConnectionState.Open Then
CN.Close()
DBStatus = ("Not Connected")
End If
SqlStr = ("Provider = Microsoft.ACE.OLEDB.12.0;Data Source =" & DBPath)
CN.ConnectionString = SqlStr
CN.Open()
Onh = Nothing
lblTime.Text = DateAndTime.Now
lblUser.Text = Login.userTB.Text
Dim sql As String
sql = "SELECT * Receipt"
Me.ReceiptTableAdapter.ClearBeforeFill = True
Me.ReceiptTableAdapter.Connection = CN
Me.ReceiptTableAdapter.Connection.CreateCommand.CommandText = sql
Me.ReceiptTableAdapter.Fill(Me.ProductListDataSet.Receipt)
Me.ReportViewer1.RefreshReport()
Me.Refresh()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
With Me.PrintForm1
.PrintAction = Printing.PrintAction.PrintToPrinter
Dim MyMargins As New Margins
With MyMargins
.Left = 0
.Right = 0
.Top = 0
.Bottom = 0
End With
.PrinterSettings.DefaultPageSettings.Margins = MyMargins
.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.CompatibleModeClientAreaOnly)
End With
End Sub
End Class