checkbox always return False vb.net - vb.net

I want to display the message "True" when i check checkbox in DatagridView but it always display "False" im looking for solution this is my code
Try
'opening the connection
con.Open()
If row.Cells(15).FormattedValue = False Then
'store your delete query to a variable(sql)
sql = "DELETE FROM terres WHERE id = '" _
& CStr(row.Cells(3).FormattedValue) & "'"
MsgBox(row.Cells(3).FormattedValue)
'Set your MySQL COMMANDS
With cmd
.Connection = con
.CommandText = sql
End With
'Execute the Data
result = cmd.ExecuteNonQuery
End If
Next
'the condition is, if the result is equals to zero
'then the message will appear and says "No Deleted Record."
'and if not the message will appear and says "The Record(s) has been deleted.."
If result = 0 Then
MsgBox("No Deleted Record.")
Else
MsgBox("The Record(s) has been deleted.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'Close the connection
con.Close()

When building your DataTable/DataGridView try something like this for the check box column:
dtdgv.Columns.Add("Process", GetType(Boolean))
'More columns etc.
'Seriously look at table adapters and
'make SURE they wont work for your application
'Fill dtdgv
DataGridView1.DataSource = dtdgv
DataGridView1.Refresh()
Then when determining whether it is checked or not something to this effect:
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Process").Value = True Then
'Stuff
End If
Next
That what you're looking for?

Related

How do I get my DataNavigator to count new number of rows after new row INSERT?

I am working on an application that creates and references the X,Y co-ordinates of a grid to an SQL server.
Mouse-tracked X-Y co-ordinates are used to search my SQL database and return the uniqueID number. If no X-Y co-ordinates are found, it then creates a new row with these co-ordinates.
Immediately after this I want it to query for the UniqueID number of the new row created and then I insert that number into the record box in the navigator (pictured as = 1). This then allows me to return the record.
My issue is the "of 23" (record count). For some reason, this does not update when I add new rows to the server, but they do appear when I restart my programme or have the form .close and then .show again.
My question is "How can I have the record count update without requiring a restart?"
Private Sub SearchSQL()
SQL.AddParam("#XLocation", VCurrentLocationX)
SQL.AddParam("#YLocation", VCurrentLocationY)
SQL.ExecQuery("SELECT * FROM Mapper_Table WHERE [X] = #XLocation AND [Y] = #YLocation;")
Try
Locations.XLocation.Text = SQL.DBDT.Rows(0).Item("X").ToString
Locations.YLocation.Text = SQL.DBDT.Rows(0).Item("Y").ToString
Locations.Current.Text = SQL.DBDT.Rows(0).Item("UniqueID")
Catch ex As Exception
'If no row exists, create it
InsertXY()
End Try
'Take UniqueID and search with it in Data Navigator ("Current")
Locations.Current.Focus()
SendKeys.Send("{ENTER}")
Locations.LocationTextBox.Focus()
'Me.Focus()
'Causes Visual Glitch
End Sub
Private Sub InsertXY()
'Add SQL Parameters and run the Commands
SQL.AddParam("#XLocation", VCurrentLocationX)
SQL.AddParam("#YLocation", VCurrentLocationY)
SQL.ExecQuery("INSERT INTO Mapper_table ([X],[Y]) " &
"VALUES (#XLocation,#YLocation);", True)
'Report and Abort
If SQL.HasException(True) Then Exit Sub
'MsgBox("A New Location has been added!")
'If SQL.DBDT.Rows.Count > 0 Then
'Dim r As DataRow = SQL.DBDT.Rows(0)
'MsgBox(r("LastID").ToString)
'End If
End Sub
'Execute Query Sub
Public Sub ExecQuery(query As String, Optional ReturnIdentity As Boolean = False)
'RESET Query Stat's
RecordCount = 0
Exception = ""
Try
DBCon.Open()
'Create Database Command
DBCmd = New SqlCommand(query, DBCon)
'Load Parameters into Database Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
'Clear Parameters before Running Next Query
Params.Clear()
'Execute Command & Fill Dataset
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
If ReturnIdentity = True Then
Dim ReturnQuery As String = "SELECT ##IDENTITY As LastID"
DBCmd = New SqlCommand(ReturnQuery, DBCon)
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
End If
Catch ex As Exception
'Capture Error
Exception = "ExecQuery Error: " & vbNewLine & ex.Message
Finally
'Close Connection
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Try
End Sub
I put this bit of code just after I generated the new row...
'Refresh Number of Rows on Record
Locations.Mapper_TableBindingSource.Filter = Nothing
Locations.Mapper_TableTableAdapter.Fill(Locations.ExcelDMDataSet.Mapper_Table)

how can i push a msgbox if record is not found in Database using vb.net

seeking help how i can push a msgbox error if a record is not in the database or no data in the database. im using vb.net and sql to check the record. not sure how to do,
here is my code
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
'Main.BGCPnl.Visible = True
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
//>Here is my code for the error message when record is not
found, im not sure what will be the right code.
i used count parameter
BGCEmp = dr(ADS.UserEmpID)
If BGCEmp.Count = 0 Then
MsgBox("no record")
Exit Sub
End If
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
You should learn how to properly use the Read method and the HasRows property of your data reader. If there can never be more than one record but there might be none then use just Read:
If myDataReader.Read() Then
'There is a row and you can access its data here.
Else
'There are no rows.
End If
If there may be multiple rows and either there can't be no rows or you don't need to do anything specific in the case that there are no rows then just use Read:
While myDataReader.Read()
'Access the current row here.
End While
If there are no rows then you never enter the loop and execution simply continues after that.
If there may be zero, one or more rows and you do need to do something specific in the case where there are none, use both HasRows and Read:
If myDataReader.HasRows Then
'There is at least one row so read the data.
While myDataReader.Read()
'Access the current row here.
End While
Else
'There are no rows.
End If
There may be situations where you only care whether there is data but you don't need the data itself. In that case, just use HasRows:
If myDataReader.HasRows Then
'There is a at least one row
Else
'There are no rows.
End If
In cases like that though, I'd suggest that you should be doing something like using a COUNT function in your query and calling ExecuteScalar rather than calling ExecuteReader.
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
End While
Else
MessageBox.Show("No Record found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
Read documentation about Read() and HasRows.

Data mismatch in criteria expression in delete oledb command

I'm simply putting the Oledb command code for delete but the problem is when I delete one of the data from the DGV and there's a message of Data type miss match in criteria expression. Here's the one of my screen shots in this problem:
Below was the codes here:
Dim com = New OleDbCommand("DELETE FROM CustInfo WHERE Customer_ID = '" & Me.Txt_CusID.Text & "'", con)
Try
com.ExecuteNonQuery()
MsgBox("Delete : SUCCESS!")
Me.Close()
ShowTable()
Txt_CusID.Text = ""
Txt_Full.Text = ""
Txt_Add.Text = ""
Txt_Con.Text = ""
Txt_Email.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Could you tell me about this problem or lacking something as soon as possible to run this command?

Update a record if it already exists in access with vb

I'm trying to check if a client is already signed in. if he is, then the button will sign him out instead of adding a new record altogether and I'm struggling to find a solution.
this is the current code I'm using:
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim cmd As New OleDbCommand
' cnn = cnn
Try
If Not cnn.State = ConnectionState.Open Then 'open the database connection
cnn.Open()
End If
If txtClientName.Text = Nothing Then 'check to see if the name field is empty
MsgBox("Please enter a name to sign in")
txtClientName.Focus()
ElseIf txtDateTime.Text = Nothing Then ' checks if timeslip is empty
MsgBox("Please enter a valid time to sign in")
txtDateTime.Focus()
Else 'if no fields are empty proceed with code
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO LogSheet (ClientName, SignInTime, CurrentDate)" &
"VALUES(?, ?, ?)"
cmd.Parameters.AddWithValue("#p1", txtClientName.Text.ToString.ToUpper)
cmd.Parameters.AddWithValue("#p2", txtDateTime.Text)
cmd.Parameters.AddWithValue("#p3", Date.Now().ToShortDateString)
cmd.ExecuteNonQuery()
RefreshData()
txtClientName.Clear()
txtDateTime.Clear()
End If
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
cnn.Close()
End Try
End Sub
there is no validation there, but ive tried many different codes with no luck..
I simply want the script to check, if client is signed in, then give an error "Client already signed in" else if he signs out, just update the signout field
thanks
This is an image of what my program is1
Update the structure of your Database Table (LogSheet) to include the following fields. ClientName,SignInTime,SignInRelation,SignOutTime,SignOutRelation,CurrentDate
If the client is signed in then the SignInTime for today (CurrentDate) will have a value, you can then populate the value for SignOutTime.
This is one possible way you could code it:
This code is untested, but you should get the idea.
Sub BtnSignIn_Click()
If IsUserLoggedIn(txtClientName.Text) = True Then
'Client has been logged in already. Do Action.
Else
'Client has not been logged in today. Do Action.
End If
End Sub
Function IsUserLoggedIn(UserName As String) As Boolean
Dim sql = "Select SignOutTime From LogSheet Where CurrentDate=#D AND ClientName=#C"
Try
Using cnn As New OleDbConnection
Using cmd As New OleDbCommand(sql, cnn)
cnn.Open()
cmd.Parameters.AddWithValue("#D", Today.Date.ToShortDateString)
cmd.Parameters.AddWithValue("#C", UserName)
Dim result = cmd.ExecuteScalar
If result Is Nothing OrElse result Is DBNull.Value OrElse String.IsNullOrEmpty(result.ToString) Then
Return False
Else
Return True
End If
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: " & System.Reflection.MethodBase.GetCurrentMethod.Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Function
You should insert DateTime values:
cmd.Parameters.AddWithValue("#p2", DateTime.Parse(txtDateTime.Text))
cmd.Parameters.AddWithValue("#p3", DateTime.Today)

How to sort datagridview columns programmatically

I am being asked to sort columns on a VB.Net created DataGridView. It's not my code but I'm trying to help. Here is part of the code:
Try
Dim sqlSelect As String = "SELECT * FROM Manpower WHERE LogOutTime IS NULL AND LogInDate = #" & dateToday & "# ORDER BY CustomerName"
Dim myDataAdapter = New OleDbDataAdapter(sqlSelect, myWorkforceConnection)
myCommandBuilder = New OleDbCommandBuilder(myDataAdapter)
myDataAdapter.Fill(myDataTable)
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
If myDataTable.Rows.Count = 0 Then
MessageBox.Show("No records found.")
Exit Sub
End If
dgvManpower.DataSource = myDataTabl
dgvManpower.Columns("ID").Visible = False
dgvManpower.Columns("EmployeeName").Width = 175
dgvManpower.Columns("EmployeeName").SortMode = DataGridViewColumnSortMode.Automatic
dgvManpower.Columns("EmployeeName").HeaderText = "Employee Name"
When I run the application I'm not able to sort on the EmployeeName column. The Microsoft documentation claims that a Glyph will be added to the column header but that doesn't appear either. How can I get the column to be "sort-able" ?
I can't see anything in your code that would stop sorting.
Check the datagridview settings in the IDE, and ensure that datagridview has Enabled=True, and ColumnHeadersVisible=True.
Then click a column header and see what happens.