Check DGV row for missing value with an sql bound back end - vb.net

I am currently working in vb.net windows express 2013 with an sql back end. I am trying to create an if statement that will look at a specific cell and make a decision based on if the cell has nothing in it or not. I think the return for an sql statement is null but im not 100% sure. I have tried lots of codes I dug up on the internet but none of them have worked for me so far. Here is the line:
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
If DGVStart.Rows(Row_Index).Cells(1).Value Is Nothing Then
This code does work, as in the windows express is telling me the line is fine, however, it seems that I am always getting the return of nothing, even if something is in the cell.I think this problem has something to do with the way i am pulling the value. I have a datagridview checkbox column which i manually added in the design form and if i change it to cells(0), which is my manually inserted column, it picks it up every time. I need to know how to tell my program to differentiate between is null and is not null.
UPDATE: I am now running into new issues after changing to searching for dbnull. here is my code.
Private Sub DGVStart_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVStart.CellContentClick
'dim start time
Dim start As String = TxtStart.Text
'fail safe so headers cant be clicked
If e.RowIndex = -1 Then
Exit Sub
End If
'dim row index and check, check is for the parts shear columns
Dim Row_Index As Integer = DGVStart.CurrentCell.RowIndex
'Dim check As String = DGVStart.Rows(Row_Index).Cells(2).Value
'if checkbox is clicked
If e.ColumnIndex = 0 Then
'---------------------------------------------Normal parts---------------------------------------------------------------
'If DGVStart.Rows(Row_Index).Cells(1).Value Then
If IsDBNull(DGVStart.Rows(Row_Index).Cells(3).Value) = True Then
Dim Shear As Date = DGVStart.Rows(Row_Index).Cells(5).Value
Dim Machine As Int16 = DGVStart.Rows(Row_Index).Cells(4).Value
Dim ShearNumber As String = DGVStart.Rows(Row_Index).Cells(1).Value
Dim Parts As String = DGVStart.Rows(Row_Index).Cells(3).Value
'Pull Values for sql statement and other operations
Try
'set up for checkbox event to trigger
If e.ColumnIndex = 0 Then
'safety messagebox
Dim result As Integer = MsgBox("Are you sure Shear Number " & ShearNumber & " is being started?", MessageBoxButtons.YesNo)
'if messagebox is no
If result = DialogResult.No Then
Exit Sub
'if messagebox is yes
ElseIf result = DialogResult.Yes Then
'sql update
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("UPDATE table1 SET " & start & " = getdate() Where col = value AND col = value", conn1)
With comm1.Parameters
.AddWithValue("#Shear", Shear)
.AddWithValue("#Machine", Machine)
End With
comm1.ExecuteNonQuery()
End Using
conn1.Close()
End Using
End If
End If
Catch ex As Exception
MsgBox(ex.ToString)
MsgBox("Error checking off start date for this machine, please contact the manufacturing enginnering department.")
End Try
Call refresh()
Call refresh2()
'--------------------------------------------------------Parts special--------------------------------------------------
Else
MsgBox("Parts")
End If
End If
End Sub
***Please note my sql statements have been modified to protect the company I am working for but I am sure the sql code works.
NEW PROBLEM: I am receiving a null error message because if i uncomment this line:
If DGVStart.Rows(Row_Index).Cells(1).Value Then
Then I am trying to see if a cell is null but that causes an error. I am trying to use my if statement to either run the normal parts, or special parts of my code.
Thanks,

Related

How to update an MS Access database using a dataset in visual basic?

Hi I am currently working on a project on visual Basic 2010, what i am stuck on now is updating my MS Access database triggered by a button click.
I already have the connection and data adapter established and i generated a data set for the data adapter, and i have used the data set. what i am trying to do is read from a data grid view entries the user have typed in and save these changes to the data set, and finally save the dataset back into the database using the oledbdataadapter.update(dataset) command. I tried everything and i have been stuck for a while, there are no errors in the code and I can see the changes made to the dataset are successful and i can view them (i am getting the "update successful" at the end of the try so i am sure the code is executing till then and not going to exception), but i simply don't see the changes in the database.
below is the code, i will appreciate any help you can offer thank you.
For j As Integer = 6 To DataGridView1.Rows.Count
Try
Dim s As String = DataGridView1.Rows(j).Cells(0).Value
Dim Quantaties As Integer = DataGridView1.Rows(j).Cells(3).Value
For i As Integer = 0 To DataSet21.Tables("Stock").Rows.Count
Dim foundRow As DataRow = DataSet21.Tables("Stock").Rows.Find(i)
If foundRow IsNot Nothing Then
If foundRow(1) = s Then
DataSet21.Tables("Stock").Rows(i).Item(7) = Quantaties
DataSet21.AcceptChanges()
Try
Dim builder As New OleDbCommandBuilder(OleDbDataAdapter1)
Me.Validate()
OleDbDataAdapter1.UpdateCommand = builder.GetUpdateCommand()
OleDbDataAdapter1.Update(DataSet21.Stock)
DataSet21.AcceptChanges()
MsgBox("Update successful")
Catch ex As Exception
MsgBox("Update failed")
End Try
End If
End If
Next
BindingSource1.EndEdit()
Catch ex As Exception
End Try
Next
thank you for your reply.
I guess both ways work OleDbDataAdapter1.Update(DataSet21.Stock) and OleDbDataAdapter1.Update("DataSet21"), because i figured out what was wrong with my code. the problem was in the DataSet21.AcceptChanges() i should not have placed it before the OleDbDataAdapter1.Update(DataSet21.Stock).
the OleDbDataAdapter.update() saves changes done in the dataset to the database and the dataset.acceptchanges() makes the dataset save the changes done to it making it seem that it doesn't have changes in it anymore. so the OleDbDataAdapter.update() was not executing since the dataset didn't have changes done to it because of the dataset.acceptchanges()
so what i did was remove dataset.acceptchanges() and it finally worked. my code looks like this now.
For j As Integer = 6 To DataGridView1.Rows.Count
Try
Dim s As String = DataGridView1.Rows(j).Cells(0).Value
Dim Quantaties As Integer = DataGridView1.Rows(j).Cells(3).Value
For i As Integer = 0 To DataSet21.Tables("Stock").Rows.Count
Dim foundRow As DataRow = DataSet21.Tables("Stock").Rows.Find(i)
If foundRow IsNot Nothing Then
If foundRow(1) = s Then
DataSet21.Tables("Stock").Rows(foundRow(0) - 2).Item(7) = Quantaties
Try
BindingSource1.EndEdit()
OleDbDataAdapter1.Update(DataSet21.Stock)
MsgBox("Update successful")
Catch ex As Exception
MsgBox("Update failed")
End Try
End If
End If
Next
Catch ex As Exception
End Try
Next

Updating Image on database MSAccess Database Vb.net?

I want to update images in the database but when i press the button it won't update , I don't have any errors on my code. I added some code in "com.executequery" block to try if i get errors, and i get messagebox result "Error"
Private Sub updatebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles updatebtn.Click
If Agetxt.SelectedItem = Nothing Or gendertxt.SelectedItem = Nothing Or Yrlvltxt.SelectedItem = Nothing Or PictureBox1.Image Is Nothing Then
MsgBox("Please do not leave required fields blanks.", vbExclamation, "Warning!")
Else
Dim memstream As New MemoryStream
Dim datapic_update As Byte()
Me.PictureBox1.Image.Save(memstream, Imaging.ImageFormat.Jpeg)
datapic_update = memstream.GetBuffer()
memstream.Read(datapic_update, 0, memstream.Length)
'to check if connection is open
If con.State = ConnectionState.Open Then
con.Close()
End If
'Updating DB
Dim editQ As String = "Update Infos SET FirstName=#f1, SurName=#f2, MiddleName=#f3, [Birthdate]=#f4, Gender=#f5, HomeAddress=#f6, CityAddress=#f7, BaranggayAddress=#f8, EmailAdd1=#f9, Birthplace=#f10, Yearlevel=#f11, Course=#f12, Emailadd2=#f13, [Age]=#f14, [Telnum]=#f15, [Mobilenum1]=#f16, [Mobilenum2]=#f17, FathersName=#f18, FathersL=#f19, MothersName=#f20, MothersL=#f21, FathersOcc=#f22, MothersOcc=#f23, StreetAdd=#f24, [Image]=#Image WHERE [StudentID]=#fid "
Dim com As New OleDbCommand(editQ, con)
con.Open()
com.Parameters.AddWithValue("#fid", Stdntid.Text.ToString)
com.Parameters.AddWithValue("#f1", fname.Text)
com.Parameters.AddWithValue("#f2", Sname.Text)
com.Parameters.AddWithValue("#f3", Mname.Text)
com.Parameters.AddWithValue("#f4", Datetxt.Value.ToShortDateString)
com.Parameters.AddWithValue("#f5", gendertxt.SelectedItem.ToString)
com.Parameters.AddWithValue("#f6", homaddtxt.Text)
com.Parameters.AddWithValue("#f7", Cityadd.Text)
com.Parameters.AddWithValue("#f8", brgyadd.Text)
com.Parameters.AddWithValue("#f9", emailaddtxt.Text)
com.Parameters.AddWithValue("#f10", birthPtxt.Text)
com.Parameters.AddWithValue("#f11", Yrlvltxt.SelectedItem.ToString)
com.Parameters.AddWithValue("#f12", coursetxt.Text)
com.Parameters.AddWithValue("#f13", emailadd2txt.Text)
com.Parameters.AddWithValue("#f14", Agetxt.SelectedItem.ToString)
com.Parameters.AddWithValue("#f15", telnumtxt.Text)
com.Parameters.AddWithValue("#f16", mobilenum1txt.Text)
com.Parameters.AddWithValue("#f17", mobilenum2txt.Text)
com.Parameters.AddWithValue("#f18", FathersL.Text)
com.Parameters.AddWithValue("#f19", fatherstxt.Text)
com.Parameters.AddWithValue("#f20", MothersL.Text)
com.Parameters.AddWithValue("#f21", motherstxt.Text)
com.Parameters.AddWithValue("#f22", fOcc.Text)
com.Parameters.AddWithValue("#f23", mOcc.Text)
com.Parameters.AddWithValue("#f24", streetadd.Text)
' image content
Dim image As OleDbParameter = New OleDbParameter("#Image", SqlDbType.Image)
image.Value = datapic_update
com.Parameters.Add(Image)
com.ExecuteNonQuery()
If com.ExecuteNonQuery > 0 Then
MsgBox("Records Successfully Updated.", vbInformation, "Updated.")
Else
MsgBox("error")
End If
End If
con.Close()
End Sub
The fact that the ExecuteNonQuery call succeeds but returns zero means that there were no records in your database that match your WHERE clause. The reason is that you're adding your parameters incorrectly.
Both the Jet and ACE OLE DB providers use positional parameters only. Even though you can give your parameters names, those names are ignored by the provider. That means that you need to add your parameters to your OleDbCommand in the same order as they appear in the SQL code. You are not.
In your SQL code, #fid is the last parameter but this is the last parameter you add to the command:
com.Parameters.AddWithValue("#f24", streetadd.Text)
That is therefore the value being used to find matching records. Rearrange the code that adds parameters to the command and add #fid last and you'll be good to go.

VB.NET - Combobox goes blank when a button is clicked, databind doesn't update

Please forgive me, it has been some time since I've used VB.Net so this may be easy.
I have a simple login form with a text box, combobox and a button. The combobox is binded to a SQL database and displays the user names from Users table. The idea is that you select a name, type in a password, and you logon to a new form (This part works Great!). If you type a wrong password, the form pops up a message that says "invalid." For some reason at this stage, the combobox goes blank. The drop down now has empty spaces where names once were. Typing in a name with a password here results in object reference errors. I have tried everything to get the combo box to reset and searched the web but nothing works!!!
(I know this is not a secure login, this is just an easy example of binding data to a combo box and checking it against SQL table). Thanks for your help!
enter code here
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BTN_Logon.Click
Try
Dim STR_User As String = Users_nameComboBox.SelectedValue
Dim STR_Pwd As String = TB_Pwd.Text
STR_User = STR_User.Trim
'MessageBox.Show(STR_User & "|" & STR_Pwd)'Used to verify this stage works
Dim numRecords As Int16 = UsersTableAdapter.FillByLogin(Me.Login_testDataSet.users, STR_User, STR_Pwd)
'MessageBox.Show(numRecords) 'Used to verify this stage works
If (numRecords > 0) Then
Dim DB_User As String = Me.Login_testDataSet.users(0).users_name.Trim
Dim DB_Pwd As String = Me.Login_testDataSet.users(0).users_pwd.Trim
'MessageBox.Show(DB_User & "|" & DB_Pwd)'Used to verify this stage works
If DB_User.Equals(STR_User) And DB_Pwd.Equals(STR_Pwd) Then
'User is authenticated for application
'This section works (removed to cleanup code)
Else
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End If
End If
MessageBox.Show("ERROR" & STR_User & "|" & STR_Pwd) 'Shows that this stage works
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
Catch ex As Exception
MessageBox.Show(ex.Message)
'Need to figure out why combobox doesn't refill, using restart for now
'Application.Restart()
End Try
End Sub
InitializeComponent
'Users_nameComboBox
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("Text",
Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataBindings.Add(New System.Windows.Forms.Binding("SelectedValue", Me.UsersBindingSource, "users_name", True))
Me.Users_nameComboBox.DataSource = Me.UsersBindingSource
Me.Users_nameComboBox.DisplayMember = "users_name"
Me.Users_nameComboBox.Name = "Users_nameComboBox"
Me.Users_nameComboBox.ValueMember = "users_name"

Display related matches from database to TextBox popup when we enter some word in textbox in vb.net

i have some problem in Vb.net , i done Google since last 2 days but not getting any related answer of my question , qtn is when user type some text in Text Box so related that text how to display popup just like when we enter some word in Google then Google show all related fields .. guys i m attaching a snapshot please help me ..
i m using vb.net as back end
and MS-Access as front end
Hey guys i got the answer
Step by step (vb.net)
1st declare this as a global
Dim lst As New List(Of String)
Dim rdrOLEDB As OleDbDataReader
Dim MySource As New AutoCompleteStringCollection()
2nd on form load or as per u r logic but make sure it comes only at one time means dont include this code in 3rd step( that is key down)
If ComboBox1.SelectedItem <> "" Then
ComboBox4.Enabled = True
cmdOLEDB.CommandText = "SELECT studentname FROM StudentDetail WHERE std = '" & ComboBox1.SelectedItem & "' "
cmdOLEDB.Connection = cnnOLEDB
rdrOLEDB = cmdOLEDB.ExecuteReader
If rdrOLEDB.Read = True Then
lst.Add(rdrOLEDB.Item(0).ToString)
While rdrOLEDB.Read
lst.Add(rdrOLEDB.Item(0).ToString)
End While
End If
rdrOLEDB.Close()
MySource.AddRange(lst.ToArray)
TextBox2.AutoCompleteCustomSource = MySource
'Auto complete mode set to suggest append so that it will sugesst one
'or more suggested completion strings it has bith ‘Suggest’ and
'‘Append’ functionality
TextBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend
'Set to Custom source we have filled already
TextBox2.AutoCompleteSource = AutoCompleteSource.CustomSource
Else
MsgBox("please select std.")
End If
3rd step that is text box key down
If e.KeyCode = Keys.Enter Then ' On enter I planned to add it the list
If Not lst.Contains(TextBox2.Text) Then ' If item not present already
' Add to the source directly
TextBox2.AutoCompleteCustomSource.Add(TextBox2.Text)
End If
ElseIf e.KeyCode = Keys.Delete Then 'On delete key, planned to remove entry
' declare a dummy source
Dim coll As AutoCompleteStringCollection = TextBox2.AutoCompleteCustomSource
' remove item from new source
coll.Remove(TextBox2.Text)
' Bind the updates
TextBox2.AutoCompleteCustomSource = coll
' Clear textbox
TextBox2.Clear()
End If ' End of ‘KeyCode’ condition
if its help full then please dont forget to click on point for other peaople search ( parden me for my bad english)

Catch Access DB Error (FormatException) And Return Custom Message?

I have an access database with a field that requires an integer. I am passing in some data that is retrieved from an Excel spreadsheet and if a string is retrieved from the cell then the calling function's Try/Catch will hit a FormatException. What I am trying to figure out is if it's possible (and it always is) to throw a custom error message that will display the cell address that contained the invalid data. Here is some example code of what I have.
Public Class Main
Private cellAddress As String
Private Sub btn_Import(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
openFileDialog.Filter = "Excel Files (*.xls)|*.xlsx|All files (*.*)|*.*"
openFileDialog.RestoreDirectory = True
If openFileDialog.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Return
End If
Try
ImportWorksheet(New FileInfo(openFileDialog.FileName))
Catch ex As FormatException
MessageBox.Show("The data contained within cell " & cellAddress & " is invalid.", "Error")
End Try
End Sub
Private Sub ImportWorksheet(ByVal excelFile As FileInfo)
Dim cnn As New OleDbConnection(My.Settings.cnn)
Dim cmd As OleDbCommand = GetCommand("UpdateSite")
Dim worksheet1 As ExcelWorksheet = package.Workbook.Worksheets(1)
Using package As New ExcelPackage(excelFile)
Using cmd.Connection
cmd.Connection.Open()
cmd.Parameters.Add("#MyData", OleDbType.Integer).Value = GetCellContents(worksheet1, "K8")
cmd.ExecuteNonQuery()
End Using
End Sub
Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String) As Object
If worksheet.Cells(address).Value Is Nothing Then
Return DBNull.Value
Else
cellAddress = address
Return worksheet.Cells(address).Value
End If
End Function
End Class
Don't think I'm missing anything here, I kind of copied and pasted and altered the code to shorten and not give up any unneeded info. Once the code hits the ExecuteNonQuery() method, the error bubbles up and says whatever I have written in. I want to pass the cell address when this happens if at all possible so they know where to look.
The only way I can think of doing this would be to add a class level variable and set it to the current cell every time it gets the value. The only issue is that since it only fires at ExecuteNonQuery(), and I have multiple parameters, if the first added parameter is invalid but the next parameter isn't, then the cell is set to the last parameter every time and I get the wrong result. Is there a way to get some kind of message back from the database that will tell me specifically which parameter didn't convert properly?
Nevermind, I just went with this for now... It works, but if you guys can give me something better, please do.
cmd.Parameters.Add("#MyData", OleDbType.Integer).Value = GetCellContents(worksheet2, "K8", "Int32")
Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String, Optional ByVal type As String = Nothing) As Object
If worksheet.Cells(address).Value Is Nothing Then
Return DBNull.Value
Else
cellAddress = address
Select Case type
Case Is = "String"
Return Convert.ToString(worksheet.Cells(address).Value)
Case Is = "Int32"
Return Convert.ToInt32(worksheet.Cells(address).Value)
Case Is = "DateTime"
Return Convert.ToDateTime(worksheet.Cells(address).Value)
Case Else
Return worksheet.Cells(address).Value
End Select
End If
End Function