Inserting ID from combo box into SQL Server using VB.net - sql-server

I have a VB form and a combobox linked to a datasource.
The database has two tables Position (SLOT, ID_WH) and Warehouse (ID_WH, WH_NAME).
The combobox is linked to the warehouse, and it shows the WH_NAME.
I need to get the ID_WH to insert into the Position table.
The code is:
WH_CB.DisplayMember = "Warehouse" 'Column name
WH_CB.ValueMember = "ID_WH" 'Column name2
'ADD INFO TO Position (SLOT)
Dim Remove_space_start As String = SLOT_TXT.Text
Dim CharStart() As Char = {" "}
Dim Stringstart As String = Remove_space_start.TrimStart(CharStart)
Dim CharEnd() As Char = {" "}
Dim StringEnd As String = Stringstart.TrimEnd(CharEnd)
Try
objconnection.Open()
cmd.Connection = objconnection
cmd.CommandText = "InsertDataIntoPosition"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("SLOT", StringEnd)
cmd.Parameters.AddWithValue("ID_WH", WH_CB.SelectedValue)
cmd.ExecuteNonQuery()
MessageBox.Show("sucess")
'Refresh DATAGRID
dgv_slot.DataSource = Nothing
dgv_slot.Refresh()
Dim str As String = "select * from Position"
Using cmd As New SqlCommand(str, objconnection)
Using da As New SqlDataAdapter(cmd)
Using newtable As New DataTable
da.Fill(newtable)
dgv_slot.DataSource = newtable
End Using
End Using
End Using
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." &
ex.Message,
"Insert Records")
Finally
objconnection.Close()
End Try
I've tried to show the whcb with a messagebox, and it shows the ID_WH, but trying to insert data into the table I get the error:
System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value 'Armazem4 ' to data type int.'
Any help?

It's solved, thank you very much.
I had the same field name (with different types) in different tables, So I was forcing the wrong one to get the information.
After I corrected that, its working fine.

Related

Cannot insert value NULL into column 'intGolferEventYearID', table does not allow nulls

I have a dialog with a combobox listing the years an event was held.
Changing the year, changes the following list boxes
One list box 'called inEvent' shows all golfers the attended said event.
The other list box called 'available' that shows every golfer we have in our database that did not attend that years event
It has two buttons. One removes golfers from 'inEvent' and moves them to 'available'. This button works.
The other button does the opposite. It adds available golfers to the selected event year. But it gives me the error -
"The statement has been terminated. Cannot insert the value NULL into column 'intGolferEventYearID', table 'dbo.TGolferEventYears'; column does not allow nulls. INSERT fails."
Changing any line of code in VB results in a different error. So I think the error has to come from SQL itself which I don't know much about. Only other thing I can think of is the listbox is giving the wrong information.
Private Sub btnAddAuto_Click(sender As Object, e As EventArgs) Handles btnAddAuto.Click
Dim strInsert As String = ""
Dim cmdInsert As OleDb.OleDbCommand ' used for our Select statement
Dim dt As DataTable = New DataTable ' table we will load from our reader
Dim intRowsAffected As Integer
' open the DB
OpenDatabaseConnectionSQLServer()
' Build the select statement
strInsert = "INSERT INTO TGolferEventYears ( intGolferID, intEventYearID) Values (" & lstAvailable.SelectedValue & ", " & cboEvents.SelectedIndex + 1 & ")"
' Retrieve all the records
cmdInsert = New OleDb.OleDbCommand(strInsert, m_conAdministrator)
intRowsAffected = cmdInsert.ExecuteNonQuery()
' close the database connection and reload the form so the changes are shown
CloseDatabaseConnection()
frmEventsGolfers_Load(sender, e)
End Sub
I separated the data access code from the user interface. This will make it easy to remove data access entirely from the Form if you later desire.
Private Sub MoveGolfer(GolfID As Integer, YearID As Integer)
'If you keep your connections local you can be sure they are
'closed and disposed which is what the Using...End Using blocks do.
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("INSERT INTO TGolferEventYears ( intGolferID, intEventYearID) Values (#Golf, #Year;")
'Always use parameters to protect against Sql injection
cmd.Parameters.Add("#Golf", SqlDbType.Int).Value = GolfID
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = YearID
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GolferID As Integer = CInt(lstAvailable.SelectedValue)
Dim Year As Integer = cboEvents.SelectedIndex + 1
Try
MoveGolfer(GolferID, Year)
Catch ex As Exception
'Catch a more specific exception and handle accordingly
MessageBox.Show(ex.Message)
End Try
End Sub
Since I don't really understand SQL I didn't realize my PK didn't have the IDENTITY tag added in the table. Adding this fixed my issue.
Here is the code I added
Dim strSelect As String
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim intNextHighestRecordID As
strSelect = "SELECT MAX(intDealerAutos) + 1 AS intNextHighestRecordID " &
" FROM TDealerAutos"
'Excute command
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
'Read result( highest ID )
drSourceTable.Read()
'Null? (Empty Table)
If drSourceTable.IsDBNull(0) = True Then
'Yes, start numbering at 1
intNextHighestRecordID = 1
Else
'No, get the next highest ID
intNextHighestRecordID = CInt(drSourceTable.Item(0))
End If
'Build the select statement
strInsert = "INSERT INTO TDealerAutos ( intDealerAutos, intDealerID, intAutoID)" &
"Values (" & intNextHighestRecordID & ", " & cboDealers.SelectedValue & ", " & lstAvailable.SelectedValue & ")"

VB.net INSERT statement not able to store data in database but got no exception?

I am trying to store data in the sql database using vb.net. In my code I am using parameters to add values..
Below is my code:
Dim lclAmount = txtQty.Text * txtUnitPrice.Text
con = New SqlConnection(connectionString)
' con.Open()
query = "INSERT INTO TBLExpensesList (ExpensesType, Purpose, Qty, UnitPrice, Amount, DoP, Description) VALUES (#val1, #val2, #val3, #val4, #val5, #val6, #val7)"
cmd = New SqlCommand(query, con)
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val1"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val2"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val3"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val4"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val5"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val6"
cmd.Parameters.Add(cmd.CreateParameter).ParameterName = "#val7"
cmd.Parameters("#val1").Value = ComboBox1.SelectedItem
cmd.Parameters("#val2").Value = txtPurpose.Text
cmd.Parameters("#val3").Value = txtQty.Text
cmd.Parameters("#val4").Value = txtUnitPrice.Text
cmd.Parameters("#val5").Value = lclAmount
cmd.Parameters("#val6").Value = dtpDOP.Value
cmd.Parameters("#val7").Value = txtDesc.Text
If con.State = ConnectionState.Closed Then
con.Open()
End If
' cmd.CommandText = query
' cmd.Connection = con
'Create Data Adaptor
' sqladp.SelectCommand = cmd
'Create & Fill Data Set
'sqladp.Fill(ds, "TBLExpensesList")
'Get Data Table
'dtbl = ds.Tables("TBLExpensesList")
cmd.ExecuteNonQuery()
If con.State = ConnectionState.Open Then
con.Close()
End If
MessageBox.Show("Data Inserted Successfully!", "", MessageBoxButtons.OK, MessageBoxIcon.None)
'Execute Command
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
I am successfully able to login into my project when the useid and passwords matches the stored values in the database. But when i try to store values I got Inserted successfully and after that When I try to read the rows I got one row.
When I close my project ad try to see the values it the database I got no value in the database..
I am also confusing that why the values are not being stored in the database????
You should read up on Working with local databases. A quote from there (emphasis mine):
At design-time, MyProject\Data.mdf is used by the data tools. At run-time, the app will be using the database under the output folder. As a result of the copy, many people have the impression that the app did not save the data to the database file. In fact, this is simply because there are two copies of the data file involved. Same applies when looking at the schema/data through the database explorer. The tools are using the copy in the project, not the one in the bin folder.

Pull value from SQL Server in VB.NET

I am attempting to pull values from an SQL Server table from VB.NET.
On VB Form 1, the number from NoTable, Row 1, is pulled successfully, and Label1 is updated with the value.
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(0)
End If
datareader.Close()
On VB Form 2 I am attempting to pull the value from the second row, using:
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
If datareader.Read() Then
Label1.Text = datareader.GetValue(1)
End If
datareader.Close()
However, this does not work, and the label is not updated with the value from the second row.
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: Index was outside the bounds of the array."
How would I go about fixing this, so that on Form 2, the value from Row 2 is pulled, and so forth?
Thank you.
Firstly, you only get one column back from the reader, but you are indexing the columns with that 0 or 1. So you should always pass 0 to GetValue.
To index the row instead, try this. Assign a form number to each form (first line in my example) and use that to determine which record to assign to the Label. There is probably a more efficient way to do this (not returning all the records before it) but this solution should fit in your environment.
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String = "SELECT Number FROM NoTable"
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Dim index = 0
While index < formNumber
If datareader.Read() AndAlso index = formNumber Then
Label1.Text = datareader.GetValue(0)
End If
index += 1
End While
datareader.Close()
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx
And another similar question in c# Access a specific row in DataReader
Another way is to just return the row you need in the first place, without iterating over the records on the client side. Assuming there is another column with an index which is in the same order as the row you want to return, called "ID"
' in form # 1
Dim formNumber = 1
Dim command As SqlCommand
Dim query As String =
"SELECT Number FROM " & _
" (SELECT Number, Row_Number() OVER (ORDER BY ID) AS RowNumber " & _
" FROM NoTable) AS Results " & _
" WHERE Results.RowNumber = " & formNumber.ToString()
command = New SqlCommand(query, con)
con.Open()
Dim datareader As SqlDataReader = cmd.ExecuteReader()
Label1.Text = datareader.GetValue(0)
datareader.Close()
See https://msdn.microsoft.com/en-us/library/ms186734.aspx
GetValue(1) does not exist, as this would refer to a second column in the select statement. You are only asking for [Number] which would be datareader.GetValue(0)

Reload a Datagrid View returns Nothing

I have the a Function that loads data into from a Microsoft Access DB into a DGV as shown in code below:
Public Sub LoaddgvCombined()
Try
'//Clear DataGrid
ds.Clear()
dgvSales.DataSource = Nothing
'dgvSales.Refresh()
dgvSales.DataSource = ds
'//Establish Connection to DB
con.ConnectionString = dbProvider & dbSource
tables = ds.Tables
con.Open()
sql = "SELECT * FROM [tblINV_SalesRecord] WHERE CDate(adddate & ' ' &addtime) < CDate('" & selectfrm & "')) ORDER BY temID ASC"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblINV_SalesRecord")
con.Close()
Dim view As New DataView(tables(0))
source1.DataSource = view
dgvSales.DataSource = view
dgvSales.AllowUserToAddRows = False
If dgvSales.RowCount < 1 Then
MessageBox.Show("No Sales Recorded Found From " & selectfrm)
End If
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
MessageBox.Show("An Error Occured While Loading Sales Record ")
End Try
End Sub
It works fine the first time, but when I call the function the second time it empties the DGV but this time it does not load any Data.
Please can anyone point out what I am doing wrong.
The thing I noticed here is that you are passing to tables BEFORE you are getting the result of your query.
Try passing the values for tables after you fill ds.
Like this:
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblINV_SalesRecord")
con.Close()
tables = ds.Tables '<=== transfer it here
It's showing empty because at the point you are passing to tables, your ds variable is not yet filled from your query.

How to make checkbox into datagridview checked based of sql database

I am new at vb.net programming ,So my question is any simple way to make each checkbox at the rows into my datagridview checked based of the database values and compare between my datagridview values and my database values and return whats the same between both as checked to the datagridview checkbox .
Thanks.
Here is my code:
Try
For Each Chckstutus As DataGridViewRow In theDataGridView.Rows
Dim ASD As String = Chckstutus.Cells(1).Value.ToString()
Dim myConnectionString As SqlConnection = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Documents\visual studio 2013\Projects\Checktools\Checktools\CheckDB.mdf;Integrated Security=True")
myConnectionString.Open()
Dim query As SqlCommand = New SqlCommand("SELECT CustomerID FROM dbo.TempPrint where CustomerID = " & ASD & "", myConnectionString)
Dim Results As String = query.ExecuteScalar().ToString()
If ASD = Results Then
Chckstutus.Cells.Item("chkbox").Value = True
Chckstutus.Cells.Item("chkbox").ReadOnly = True
Else
Chckstutus.Cells.Item("chkbox").Value = False
Chckstutus.Cells.Item("chkbox").ReadOnly = False
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try

Resources