Fromat datagridview cells based on SQL logic - sql

I have the following SQL statement that checks for duplicate date ranges within my data set.
SELECT *
FROM [DaisyServices].[dbo].[DaisyServicesIndigo] i
JOIN [DaisyServices].[dbo].[DaisyServicesIndigo] i2
on i.cli = i2.cli
and i.quantity = i2.quantity
and i.unitcost = i2.unitcost
and i.totalcost = i2.totalcost
and i.[description] = i2.[description]
and ((i.FromDate <= i2.ToDate) and (i.ToDate >= i2.FromDate))
WHERE i.id<>i2.id
AND (i2.[bill]=0 AND i2.[Billed Month] is Null AND i2.currentbill = 0)
I would like to use this SQL logic, to check each line of my data grid view and then format each line accordingly if the condition is met. i.e. the data ranges overlap.
Something like this, I am just not sure how to incorporate the SQL element?
For Each row As DataGridViewRow In DaisyServicesForm.DataGridView2.Rows
If "SQL condition for the specific line is true" Then
row.DefaultCellStyle.ForeColor = Color.Blue
End If
Next
Any help greatly appreciated.

Try this piece of code
For intcount=0 to DaisyServicesForm.DataGridView2.Rows.count-1
If checkdata(intcount)=true Then
datagridview2.rows(intcount).DefaultCellStyle.ForeColor = Color.Blue
End If
Next
and add a checking function in your code like:
Private Function checkdata(ByVal row As Integer) As Boolean
Dim da As SqlDataReader
Dim command As SqlCommand
command.CommandType = CommandType.Text
command.Connection = connection
command.CommandText = "Your query for checking if the item in specified row is in database"
da = command.ExecuteReader
If da.HasRows Then
Return True
Else
Return False
End If
End Function
specify the checking in the command text in fucntion.Just Provided this as an example,you may modify it upon our own needs.

Related

Extracting the First (Oldest) Value from Dataset Based on Column Value

I don't have a great deal of experience working with DataSets and haven't been able to find the best way of achieving what I want to achieve.
I basically create a DataSet using a SQL Query and then I am trying to find a Specific Value in the 'Field' column and then if there is a 'Y' in the 'Flag' (as apposed to a 'N') Column on the same Row then I want it to change a check box's state to Checked as well as updating a labels text.
What I have seems to work however if no data is returned I get the below error:
Object reference not set to an instance of an object
If I change the code slightly from .FirstOrDefault() to .First() I get this error:
Sequence contains no elements
The part of the code that appears to be causing the problem is listed below. If you need to know anything else I will add it in.
Dim sSQL As String
sSQL =
<SQL>
SELECT MAX(UpdateTime) AS UpdateTime FROM AdminCS_Data_Current
WHERE UpdateUser = |##UpdateUser|
</SQL>
sSQL = Replace(sSQL, "##UpdateUser", AdminCB.Text)
Me.LastUserUpdate.Text = "Last Action: " & Format(ReturnDatabaseValue(sSQL, "UpdateTime", "Data"), "dd/MM/yyyy HH:mm:ss")
Dim EmployeeDataset As New DataSet
Try
sSQL =
<SQL>
SELECT * FROM AdminCS_Data_Current
WHERE UpdateUser = |##UpdateUser| AND CONVERT(DATE, UpdateTime) = CAST(GETDATE() AS DATE)
ORDER BY UpdateTime ASC
</SQL>
sSQL = Replace(sSQL, "##UpdateUser", AdminCB.Text)
EmployeeDataset = ReturnDataSet(sSQL, "Data")
If EmployeeDataset IsNot Nothing Then
Dim eData = EmployeeDataset.Tables(0)
If (eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()("Flag")) IsNot Nothing Then
If eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()("Flag").ToString.Trim = "Y" Then
TShtY.CheckState = CheckState.Checked
TShtTime.Text = Format(eData.Select("Field = 'Timesheets Checked'").First()("UpdateTime"), "HH:mm:ss")
Else
TShtN.CheckState = CheckState.Checked
End If
End If
' The above two IF statements would be repeated several times on each change of "Field"
End If
It would appear that this code has introduced not just iunefficiency but also a bug:
If (eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()("Flag")) IsNot Nothing Then
If eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()("Flag").ToString.Trim = "Y" Then
TShtY.CheckState = CheckState.Checked
TShtTime.Text = Format(eData.Select("Field = 'Timesheets Checked'").First()("UpdateTime"), "HH:mm:ss")
Else
TShtN.CheckState = CheckState.Checked
End If
End If
It should have been written like this in the first place:
Dim row = eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()
If row IsNot Nothing Then
If row("Flag").ToString.Trim = "Y" Then
TShtY.CheckState = CheckState.Checked
TShtTime.Text = Format(row("UpdateTime"), "HH:mm:ss")
Else
TShtN.CheckState = CheckState.Checked
End If
End If
Easier to read, more efficient and avoids that nasty bug.
Also, I'd much rather see this:
Dim row = eData.Select("Field = 'Timesheets Checked'").FirstOrDefault()
If row IsNot Nothing Then
If row("Flag").ToString.Trim = "Y" Then
TShtY.Checked = True
TShtTime.Text = CDate(row("UpdateTime").ToString("HH:mm:ss")
Else
TShtN.Checked = True
End If
End If
You should never use the CheckState of a Checkbox unless it's tri-state, which maybe yours are but I doubt it. As for Format, we're not in VB6 anymore Toto.

Referencing an entire data set instead of a single Cell

I am creating a login form for users to log into using a database. I was wondering if there is a way in which i could get the program to search the entire table instead of a certain item. Here is my code so far.
Dim UserInputtedUsername As String
Dim UserInputtedPassword As String
UserInputtedUsername = txtAdminUsername.Text
UserInputtedPassword = txtAdminPassword.Text
sqlrunnerQuery = "SELECT * FROM tblLogin"
daRunners = New OleDb.OleDbDataAdapter(sqlrunnerQuery, RunnerConnection)
daRunners.Fill(dsRunner, "Login")
If UserInputtedUsername = dsadminlogin.Tables("Login").Rows(0).Item(2) And UserInputtedPassword = dsadminlogin.Tables("Login").Rows(0).Item(3) Then
Form1.Show()
ElseIf MsgBox("You have entered incorrect details") Then
End If
End Sub
Instead if searching the (in-memory) DataSet for your user serach the database in the first place. Therefore you have to use a WHERE in the sql query(with guessed column names):
sqlrunnerQuery = "SELECT * FROM tblLogin WHERE UserName=#UserName AND PassWord=#PassWord"
Note that i've used sql-parameters to prevent sql-injection. You add them in this way:
daRunners = New OleDb.OleDbDataAdapter(sqlrunnerQuery, RunnerConnection)
daRunners.SelectCommand.Parameters.AddWithValue("#UserName", txtAdminUsername.Text)
daRunners.SelectCommand.Parameters.AddWithValue("#PassWord", txtAdminPassword.Text)
Now the table is empty if there is no such user.
If dsadminlogin.Tables("Login").Rows.Count = 0 Then
MsgBox("You have entered incorrect details")
End If
For the sake of completeteness, you can search a complete DataTable with DataTable.Select. But i prefer LINQ-To-DataSet. Here's a simple example:
Dim grishamBooks = From bookRow in tblBooks
Where bookRow.Field(Of String)("Author") = "John Grisham"
Dim weHaveGrisham = grishamBooks.Any()

"No data exists for the row/column." executing OLEDB Oracle OleDbDataReader

I know this is very basic, and I've done this hundreds of times. But, for some strange reason I am executing this command on a database, and it fails when it tries to read a column from the result. If I execute this statement in SQL Plus logged in as the same credentials, the row (table has 1 row) is selected just fine. Any ideas what I am doing wrong? I tried accessing the columns by name, by index, and indeed any column - all of them give no data. I tried without the .NextResult() (just in case), same exception.
'...
' Determine if this database is Multisite enabled
Dim multisiteCmd As OleDbCommand = DbConnection.CreateCommand
multisiteCmd.CommandText = "SELECT * FROM TDM_DB_VERSION;"
Dim dbVersionReader As OleDbDataReader = multisiteCmd.ExecuteReader()
If dbVersionReader.HasRows Then
dbVersionReader.NextResult()
'If a ReplicaID was generated for the Database ID, then this is part of a
'multisite implementation
'Dim dbRepID As String = dbVersionReader("DB_REPLICID")
Dim dbRepID As String = dbVersionReader(9)
PluginSettings.UseMultisite = False
If Not dbRepID Is Nothing Then
If dbRepID.Length > 0 Then
PluginSettings.UseMultisite = True
PluginSettings.MultisiteReplicaId = dbRepID
End If
End If
End If
dbVersionReader.Close()
As you can see from these Immediate commands, the connection is open:
? DbConnection.Provider
"OraOLEDB.Oracle"
? DbConnection.State
Open {1}
NextResult() is for statements that have more than one result set. For example, if you had sent a command like this:
"SELECT * FROM TDM_DB_VERSION;SELECT * FROM dual;"
Note there are two queries in there. You can handle them both with a single call to the database and a single OleDbDataReader, and NextResult() is part of how you do that.
What you want instead is this:
Dim multisiteCmd As OleDbCommand = DbConnection.CreateCommand
multisiteCmd.CommandText = "SELECT * FROM TDM_DB_VERSION;"
Dim dbVersionReader As OleDbDataReader = multisiteCmd.ExecuteReader()
If dbVersionReader.Read() Then
'If a ReplicaID was generated for the Database ID, then this is part of a
'multisite implementation
'Dim dbRepID As String = dbVersionReader("DB_REPLICID")
Dim dbRepID As String = dbVersionReader(9)
PluginSettings.UseMultisite = False
If Not dbRepID Is Nothing Then ' Do you mean check for DbNull here? "Nothing" is not the same thing
If dbRepID.Length > 0 Then
PluginSettings.UseMultisite = True
PluginSettings.MultisiteReplicaId = dbRepID
End If
End If
End If
dbVersionReader.Close()

SQL QUERY Return 0 Records but 2 records exist

This code returns zero rows count but there are 2 rows in appointment table.
The msgbox I commented was to check if the date is correct and format is correct and shows date as 2014/08/09. The appointment date in database is 2014/08/09 for 2 records (the only 2 records). Record count variable shows 0.
Table name (copied directly cut and paste) is Appointments and column is AppointmentDate.
The connectDatabase sub routine connects to the database successfully as I use it whenever I connect to database so it's correct as I connect to other tables correctly before I run this code using same sub routine.
Command.text contains
SELECT * FROM Appointments WHERE AppointmentDate = 2014/08/09
Don't know what other details to specify.
Private Sub frmAppointments_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'load appointments
LoadAppointments(dtpAppointmentDate.Value.Date)
End Sub
Public Sub LoadAppointments(whichdate As Date)
Dim sqlcmd As New OleDb.OleDbCommand
'set connection
ConnectDatabase()
With frmAppointments
'MsgBox(whichdate)
M_connDB.Open()
'fetch records from database
sqlcmd.Connection = M_connDB
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate = " & whichdate
.dataAdapterAppointments = New OleDb.OleDbDataAdapter(sqlcmd.CommandText, M_connDB)
'first clear data table to prevent duplicates
.dataTableAppointments.Rows.Clear()
.dataAdapterAppointments.Fill(.dataTableAppointments)
M_connDB.Close()
Dim rowindex As String
Dim iy As Long
Dim recordcount As Long
'check if any records exist
recordcount = .dataTableAppointments.Rows.Count
If Not recordcount = 0 Then
For iy = 0 To .dataTableAppointments.Rows.Count
For Each row As DataGridViewRow In .dtgrdAppointments.Rows
If row.Cells(0).Value = .dataTableAppointments.Rows(iy).Item(6) Then
rowindex = row.Index.ToString()
MsgBox(.dtgrdAppointments.Rows(rowindex).Cells(0).Value, vbInformation + vbOKOnly, "MSG")
Exit For
End If
Next
Next iy
Else
MsgBox("No Appointments for selected date.", vbInformation + vbOKOnly, "No Appoinments")
End If
End With
Use sql-parameters instead of string-concatenation. This should work in MS Access:
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate = ?"
sqlcmd.Parameters.AddWithValue("AppointmentDate", whichdate)
This prevents you from conversion or localization issues and -even more important- sql-injection.
2014/08/09 doesn't have quotes around it, making it a math expression (2014 divided by 8 divided by 9). Of course, your table has no rows with a date matching the result of that expression. But don't put in the quotes. Instead, add a parameter.
I don't VB, so I write it in C#. My point of view is it's better to specify the datatype too:
sqlcmd.CommandText = "SELECT * FROM Appointments WHERE AppointmentDate=#whichdate";
sqlcmd.Parameters.Add("#whichdate", SqlDbType.Date).Value = whichdate;

new records to add first row of datagrid view in vb.net

In my VB.Net application I am filling my data grid view like this:
Dim cmdd1 As New SqlCommand("DashBordFetch1", con.connect)
cmdd1.CommandType = CommandType.StoredProcedure
cmdd1.Parameters.Add("#locid", SqlDbType.Int).Value = locid
da1.SelectCommand = cmdd1 dr = cmdd1.ExecuteReader
While dr.Read
flag = False
carid1 = dr("Car_Id")
For j = 0 To dcnt1 - 2
If carid1 = dgv.Item(0, j).Value Then
flag = True
Exit For
End If
Next
If flag = False Then
If dr("Car_Id") Is DBNull.Value Then
carid1 = "null"
Else
carid1 = dr("Car_Id")
End If
If dr("Plate_Source") Is DBNull.Value Then
platesource1 = "Null"
Else
platesource1 = dr("Plate_Source")
End If
Dim row1 As String() = {carid1, platesource1}
DGVDeliverd.Rows.Add(row1)
End If
End While
..also i am using Timer..every 2 minutes timer will work .some time new records will added to my datagridview..while adding new record that is adding to last row of my datagrid view,,i want to add every time new records to my first row of datagridview. how i can do this?
I am using windows forms
You can use Insert instead of Add to specify the position for the new row. So always insert at position zero:
DGVDeliverd.Rows.Insert(0, row1)
See MSDN here for details (screenshot below).
Use:
Order by your primary id desc
to keep the latest data on top of the grid
update #1
DGVDeliverd.Controls[0].Controls.AddAt(0, row1);