BC30469: Reference to a non-shared member requires an object reference - vb.net

I am trying to write code that uses user input to query a data base and then display a GridView in VB 2015. I am getting a compilation error and cannot figure out what I an doing wrong.
Here is all my .VB coding. I have intentionally set variable to defined numbers for testing purposes.
Imports System.Data
Imports System.Data.SqlClient
Partial Class BeaversInc_GridTest
Inherits System.Web.UI.Page
Dim strConnectionString As String
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim conn As New SqlConnection(strConnectionString)
Dim drDataReader As SqlDataReader
Dim dtDataTable As New DataTable
Dim cmd As New SqlCommand
Dim intStoreNumber As Integer
Dim dteStartDate As Date
Dim dteEndDate As Date
intStoreNumber = "686"
dteStartDate = CDate("11/15/2013")
dteEndDate = CDate("11/15/2015")
conn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString
cmd.Connection = conn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "CriticalFails"
With cmd.Parameters
.AddWithValue("#StoreNumber", intStoreNumber)
.AddWithValue("#StartDate", dteStartDate)
.AddWithValue("#Enddate", dteEndDate)
End With
conn.Open()
drDataReader = SqlCommand.ExecuteReader
dtDataTable.Load(drDataReader)
GridView1.DataSource = dtDataTable
GridView1.DataBind()
conn.Close()
End If
End Sub
End Class

The line "drDataReader = SqlCommand.ExecuteReader" was not supposed to be "drDataReader = cmd.ExecuteReader"??
I think that is your problem. =D

Related

How to display multiple results from a users' input from filters using MS Access and Visual Basic

I'm struggling to grasp VB as I'm new to programming. I am creating a program which displays a result (namely a link to a website) based on a users' filters. I've done this so far, which just selects the size filter. However, I don't know how to write the code that will check the database for the users' preference and output an appropriate link in the form of a label. Is it as simple as just printing DataTable or am I totally wrong? Any help would be greatly appreciated.
Here is my code so far:
Imports System.Data.OleDb
Public Class frmFilters
Dim provider As String
Dim dataFile As String
Dim ConnString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private ConStr As String = "My Connection String"
Private Sub buttonSearch_Click(sender As Object, e As EventArgs) Handles buttonSearch.Click
provider = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "H:\Visual studio files\Project\CMPC\partLists.accdb"
End Sub
Private Function GetPartData(filterMicroATX As Integer, filterATX As Integer) As DataTable
Dim dt As New DataTable
Dim sql = "SELECT * FROM partList WHERE
[size] > #MicroATX
And [size] < #ATX;"
Using con As New OleDbConnection(ConStr),
cmd As New OleDbCommand(sql, con)
With cmd.Parameters
.Add("#MicroATX", OleDbType.Integer).Value = filterMicroATX
.Add("#ATX", OleDbType.Integer).Value = filterATX
End With
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub btnQuit_Click(sender As Object, e As EventArgs) Handles btnQuit.Click
Me.Close()
End Sub
End Class

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..

how to insert checked items from checkedlistbox to SQL database?

I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.

VB.Net OleDBConnection code to update access database from DataGridView

I have a simple userform with a DataGridView and I would like to use OleDB code to update the accdb database based on any entries made in the gridview. The load button works fine, but the save button produces this error:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Here is my code:
Imports System.Data.OleDb
Public Class Form1
Dim myConString As String
Dim con As OleDbConnection = New OleDbConnection
Dim Dadapter As OleDbDataAdapter
Dim DSet As DataSet
Dim DSet2 As DataSet
Dim ConCMD As OleDb.OleDbCommand
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Psmccsfs01\snd\PRODUCTION\Licensed\Reporting\FTO Adjustment Tools\FTO_Log_DB.accdb;"
con.ConnectionString = myConString
con.Open()
Dadapter = New OleDbDataAdapter("select * from FTO_Log", con)
DSet = New DataSet
Dadapter.Fill(DSet, "FTO_Log")
DataGridView1.DataSource = DSet.Tables("FTO_Log")
con.Close()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Using con = New OleDbConnection(myConString)
con.Open()
Dadapter.Update(DSet, "FTO_Log")
End Using
End Sub
End Class
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
notice the typo in the code above, straight from the msdn site ;p
short and simple: http://msdn.microsoft.com/en-us/library/33y2221y%28v=vs.110%29.aspx

vb database connection gives no information as to whether connection was successful

I am trying to connect to an access database THROUGH CODE. I capitalized that last bit because I am well aware of the visual method of doing it but can't use that method in this instance. Basically I just want to create a databinding to a combobox on a single column from a table Title that displays the column Year. To clear that up I want to populate cboYearsFillBy with the data from the column YearPublished. The thing I am finding to be the biggest pain is that vb doesn't throw any sort of fuss when the db isn't found so I don't even know if it is finding it. My code is below
Imports System.Data.OleDb
Public Class frmTitle
' Create untyped dataTables
Dim dtYears As New DataTable
' Declare a variable to represent the DataAdapter
Dim daYears As OleDbDataAdapter
' Create BindingSource objects for Employee & Dept tables:
Dim WithEvents bsYears As New BindingSource
Private Sub frmTitle_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connStr As String = "Provider=Microsoft.ace.OLEDB.12.0;Data Source=D:\VisualStudioProjects\Biblio.accdb"
MessageBox.Show(connStr)
Dim titleSQLStr As String = "SELECT * FROM Title"
daYears = New OleDbDataAdapter(titleSQLStr, connStr)
Dim commandBuilder As New OleDb.OleDbCommandBuilder(daYears)
daYears.Fill(dtYears)
dtYears.PrimaryKey = New DataColumn() {dtYears.Columns("YearPublished")}
bsYears.DataSource = dtYears
cboYearsFillBy.DataSource = bsYears
cboYearsFillBy.DisplayMember = "YearPublished"
cboYearsFillBy.ValueMember = "YearPublished"
End Sub
End Class
I get the following output
Imports System.Data.OleDb
Public Class frmTitle
' Create untyped dataTables
Dim dtYears As New DataTable
' Declare a variable to represent the DataAdapter
Dim daYears As OleDbDataAdapter
' Create BindingSource objects for Employee & Dept tables:
Dim WithEvents bsYears As New BindingSource
Private Sub frmTitle_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connStr As String = "Provider=Microsoft.ace.OLEDB.12.0;Data Source=D:\VisualStudioProjects\Biblio.accdb; Persist Security Info=True"
MessageBox.Show(connStr)
Dim con As New OleDbConnection
con = New OleDbConnection(connStr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim titleSQLStr As String = "SELECT * FROM Title"
daYears = New OleDbDataAdapter(titleSQLStr, connStr)
daYears.Fill(dtYears)
cboYearsFillBy.DataSource = dtYears
cboYearsFillBy.DisplayMember = "YearPublished"
cboYearsFillBy.ValueMember = "YearPublished"
con.Close()
End Sub
End Class
I simplified your code just try now