DataGridView add row - vb.net

enter image description hereI am trying to add rows to DataGridView which I suceeded but I have one column unbounded where some math take place.
I want sum of that column below it.
Note: Cell(10) is the one unbounded. In this case I get an error:
Column does not exist
(obviously, it is not in datatable). Here is my code:
Public Sub PrintData()
PrintSQL.ExecQuery("SELECT * FROM Cisnik WHERE Datum = '" &
CDate(LB2.Text).ToString("MM.dd.yyyy") & "'; ")
If PrintSQL.HasException(True) Then Exit Sub
DGV3Print.DataSource = PrintSQL.DBDT
For Each r As DataGridViewRow In DGV3Print.Rows
r.Cells(10).Value = (r.Cells(1).Value - r.Cells(2).Value - r.Cells(4).Value - r.Cells(6).Value)
tb = tb + r.Cells(10).Value
Next
Dim myrow = PrintSQL.DBDT.NewRow
myrow(0) = "CELKEM"
myrow(10) = tb
PrintSQL.DBDT.Rows.Add(myrow)
End Sub
I will appreciate any suggestions

Is your Datum column really stored in the database as a string? You really shouldn't be concatenating strings to build an SQL query. Learn to use parameters. Why take a string, convert it to a Date then back to a string? To solve your problem simply let the database do the work. This just demonstrates the pattern to use. Then bind to your grid.
Dim s = "Select Num1, Num2, Num3, Num1 + Num2 + Num3 As Total From Numbers;"

I solved it this way: It may be amateurish because I am total beginer but it actualy works in way I need. The code is:
Dim myrow = PrintSQL.DBDT.NewRow
Dim i As Integer
i = DGV3Print.Rows.Count - 1
DGV3Print.Rows(i).Cells(0).Value = "CELKEM"
DGV3Print.Rows(i).Cells(10).Value = tb
PrintSQL.DBDT.Rows.Add(myrow)
Anyway thanks for your suggestions

A much simpler way to add a row to a DataGridView is:
DataGridView.Rows.Add({Data1,Data2})

To add a row to a DateGridView, see the example below.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class
http://vb.net-informations.com/datagridview/vb.net_datagridview_database.htm
I'm know you can sum data points in a DataGridView, but I haven't done this for a very long time. Something like this should be pretty close...
Dim sum As Integer = 0
For i As Integer = 0 To dataGridView1.Rows.Count() - 1 Step +1
sum = sum + dataGridView1.Rows(i).Cells(2).Value
Next
textBoxSum.Text = sum.ToString()

Related

VB.Net, Problem updating table from DataGridView

This is my first post so forgive me if I goof!
I am trying to update myself from VBA to VB.Net. Using loads of help from Google etc I am doing Ok except when I try to update my table from a DataGridView. It just does not update. What I would like is that a cell is update on change. My code so far is shown (I have tried all sorts of builder, tables etc so my code may have a smattering of these that are redundant):
Imports System.Data.SqlClient
Imports System.IO
Imports Microsoft.SqlServer
Public Class FrmData
Private dsS As DataSet = New DataSet
Private adpS As SqlDataAdapter
Private builder As SqlCommandBuilder
Private bsource = New BindingSource
Private Sub FrmData_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
Dim sqlS = "SELECT [Data].[Date] AS [Date] ,
[Data].[PaidBy] AS [Paid By] ,
[Data].[PaidAmount] AS [Paid Amount (£)],
[Data].[AmountLeft] AS [Amount Left (£)]
FROM [Data] WHERE [Data].[Name]= '" & strName & "'
ORDER BY [Data].[Date] DESC"
Dim adpS As SqlDataAdapter
adpS = New SqlDataAdapter(sqlS, connection)
builder = New SqlCommandBuilder(adpS)
Dim dTable As New DataTable
bsource.DataSource = dTable
bsource.EndEdit()
adpS.Fill(dTable)
connection.Close()
DataGridView1.DataSource = dTable
End Sub
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
Dim x As Integer = 0
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New SqlCommandBuilder(adpS)
Dim rowsAffected As Integer = adpS.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
End Class
Any help would be appreciated.
This is for SQL Server, right. Try it like this.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class
After two days working on this, I finally got it right for myself! Also, I had an eye on #ryguy72 codes as well. these are the steps you can take to get there:
Step 1: Drag and drop DataGridView into your form
Step 2: In the App.config add this between configuration:
<connectionStrings>
<add name="ehsanConnection" connectionString="Data Source=XXX
; User= XX; Password= XXX" ProviderName="System.Data.SqlClient"/>
</connectionStrings>
Step 3: The code below shows how you can get the DataGridView programmatically right, it worked perfectly fine for me.
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Dim connStr As String =
ConfigurationManager.ConnectionStrings("ehsanConnection").ToString
Dim connStri = New SqlConnection(connStr)
Dim sql As String = "SELECT * FROM [Ehsan].[dbo].[Data]"
sCommand = New SqlCommand(sql, connStri)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Data")
sTable = sDs.Tables("Data")
connStri.Close()
DataGridView1.DataSource = sDs.Tables("Data")
The main point here was that I had to use [Ehsan].[dbo].[Data] not only the name of the table, "Data". Actually, it didn't work for me that way and it kept complaining!
Step 4: If you want to update your database after you changed some of the records in datagridview, use this code :
sAdapter.Update(sDs.Tables(0))
Main important point is that: "you have to set a primary key in your table first otherwise it won't work!"

Trying to get SUM of ListBox selected items from local DataTable into a Label

I have been searching for days, for any possible reference or suggestions and everything I've come across hasn't worked.
The goal:
User will select options in ComboBox1 that will then determine the available options in ComboBox2, then will populate a list of operations in ListBox1.
When the user selects available operations in ListBox1, I need the output to be the sum of values (total time in minutes in this case) into a label for display.
The data used in stored in a local db. So far everything works with my comboboxes and the listbox.
Im attempting to get the Text value, of all selected items, in ListBox1 to output the numeric value in my table (column 4 "OperationsTime"), into a label that will display the sum of all the selections (Total Time In Minutes).
Some Things I have Tried From Other Posts:
Label9.Text = ListBox1.ValueMember
Label9.Text = ListBox1.ValueMember.ToString
Label9.Text = CType(ListBox1.SelectedItem, DataRowView).Row.Item("OperationsTime").ToString
Attempted using Double:
Dim Total As Double = 0
For Each Time As Integer In ListBox1.SelectedItems
Total += CDbl(Time.ToString.Substring(Time.ToString.LastIndexOf(",") + 1))
Next
Label9.Text = Total.ToString
Screen Shot of the Table:
Operations Data Table
Below is my code:
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class MainHome
Private Function GetData(ByVal sql As String) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = Me.GetData("SELECT SizeId, SizeName FROM Size")
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ComboBox3.Enabled = False
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox3.DataSource = Nothing
ComboBox2.Enabled = False
ComboBox3.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT DetailLevelId, DetailLevelName FROM DetailLevel WHERE SizeId = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = Me.GetData(sql)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT OperationsId, OperationsName, OperationsTime FROM Operations WHERE DetailLevelId = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = Me.GetData(sql)
ListBox1.ValueMember = "OperationsName"
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
Label9.Text = CType(ListBox1.SelectedValue, Integer).ToString
'Label.Text = CType(cbbank.SelectedItem, DataRowView).Row.Item("Account").ToString
End IF
End Sub
Dim totalOperationsTime As Double
For Each view As DataRowView In ListBox1.SelectedItems
totalOperationsTime += CDbl(view("OperationsTime"))
Next
There's no need to get the DataRow from the DataRowView because you can access the field values directly from the DataRowView. It can and does do many of the same things that the DataRow does.
That's the most conventional way but there are other options too. You could throw some LINQ at it:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of DataRowView)().
Sum(Function(view) CDbl(view("OperationsTime")))
It is somewhat annoying that the ValueMember property only helps you get a value for the SelectedItem. Here's a class I wrote some time ago that adds a GetItemValue method that makes use of the ValueMember much as the GetItemText method does for the DisplayMember:
Public Class ListBoxEx
Inherits ListBox
Public Function GetItemValue(item As Object) As Object
Dim index = Me.Items.IndexOf(item)
If (index <> -1 AndAlso Me.DataManager IsNot Nothing) Then
Return Me.FilterItemOnProperty(Me.DataManager.List(index), Me.ValueMember)
End If
Return Nothing
End Function
End Class
If you use that control instead of a regular ListBox then you can do this:
Dim totalOperationsTime As Double
For Each item In ListBoxEx1.SelectedItems
totalOperationsTime += CDbl(ListBoxEx1.GetItemValue(item))
Next
or this:
Dim totalOperationsTime = ListBox1.SelectedItems.Cast(Of Object)().
Sum(Function(item) CDbl(ListBoxEx1.GetItemValue(item)))
One advantage of using that custom control is that you don't have to know what type the data source or its items are. You only have to know that the ValueMember has been set.
I made a few changes to your code. It works with a ListBox. See comments for details.
' "Please Select" doesn't work well in the ListBox, I added it as an option
Private Shared Function GetData(ByVal sql As String, insertPleaseSelect As Boolean) As DataTable
Dim constr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\hartj\Documents\visual studio 2015\Projects\TIMEMATRIX2.0\TIMEMATRIX2.0\TMX.mdf;Integrated Security=True"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
If insertPleaseSelect Then
Dim row As DataRow = dt.NewRow()
row(0) = 1
row(1) = "Please Select"
dt.Rows.InsertAt(row, 0)
End If
Return dt
End Using
End Using
End Function
Private Sub MainHome_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
ComboBox1.DataSource = GetData("SELECT [SizeId], [SizeName] FROM [Size]", True)
ComboBox1.DisplayMember = "SizeName"
ComboBox1.ValueMember = "SizeId"
ComboBox2.Enabled = False
ListBox1.SelectionMode = SelectionMode.MultiSimple ' allow multi-select
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
ComboBox2.DataSource = Nothing
ComboBox2.Enabled = False
If ComboBox1.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [DetailLevelId], [DetailLevelName] FROM [DetailLevel] WHERE [SizeId] = {0}", ComboBox1.SelectedValue)
ComboBox2.DataSource = GetData(sql, True)
ComboBox2.DisplayMember = "DetailLevelName"
ComboBox2.ValueMember = "DetailLevelId"
ComboBox2.Enabled = True
End If
End Sub
Private Sub ComboBox2_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox2.SelectionChangeCommitted
ListBox1.DataSource = Nothing
ListBox1.Enabled = False
If ComboBox2.SelectedValue.ToString() <> "0" Then
Dim sql As String = String.Format("SELECT [OperationsId], [OperationsName], [OperationsTime] FROM [Operations] WHERE [DetailLevelId] = {0}", ComboBox2.SelectedValue)
ListBox1.DataSource = GetData(sql, False)
ListBox1.DisplayMember = "OperationsName" ' changed this from ValueMember to DisplayMember
ListBox1.ValueMember = "OperationsTime"
ListBox1.Enabled = True
ListBox1.ClearSelected() ' Every time the ListBox is populated, clear it
End If
End Sub
' Added this handler to respond to user input, not programmatic selection changes
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
' Here is the sum
Label9.Text = ListBox1.SelectedItems.OfType(Of DataRowView).Sum(Function(o) CType(o("OperationsTime"), Double))
End Sub

UPDATE Database from Listview checked items

Hellos guys.
I'm trying to update my database from only checked/selected items in my listview, so here is my code that is not working because updates all records. I tried everything... Please any help could be great!
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\bnp\Desktop\Servicios1.mdb"
Dim myconnection As New OleDbConnection(constring)
Dim sql As String = ""
Dim estado As String = "Saved"
myconnection.Open()
If ListView1.CheckedItems.Count > 0 Then
Dim x = ListView1.CheckedItems.ToString
sql = "UPDATE Pedidos SET Ped_est = #estado where x = #x"
Dim acscmd = New OleDb.OleDbCommand(sql, myconnection)
acscmd.Parameters.AddWithValue("#estado", estado)
acscmd.Parameters.AddWithValue("#x", x)
acscmd.ExecuteNonQuery()
End If
myconnection.Close()
End Sub
I'm trying to update my database from only checked/selected items in my listview
if You want to update just Select items You must Make (For)
For II As Integer = 0 To ListView1.SelectedItems.Count - 1
sql = "UPDATE Pedidos SET Ped_est = #estado where x
= '" & ListView1.SelectedItems.Item(II).SubItems(0).Text & "'"
your code Here
Next
i hope this Code good for you
Just solve my problem... Here is the code if someone have the same issue ty ;).
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\bnp\Desktop\Servicios1.mdb"
Dim myconnection As New OleDbConnection(constring)
Dim sql As String = ""
Dim estado As String = "Saved"
myconnection.Open()
For Each item As ListViewItem In ListView1.Items
If item.Checked Then
Dim x = item.SubItems(0).Text
sql = "UPDATE Pedidos SET Ped_est = #estado WHERE Id = #x"
Dim acscmd = New OleDb.OleDbCommand(sql, myconnection)
acscmd.Parameters.AddWithValue("#estado", estado)
acscmd.Parameters.AddWithValue("#x", x)
acscmd.ExecuteNonQuery()
End If
Next
myconnection.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For x As Integer = 0 To ListView1.Items.Count - 1
' For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(x).Checked = True Then
Dim Stradd12 As String = "INSERT INTO `tbl_student_attendence` ([student_id],[Student_Name],[Activities],[pDate],[pDay],[Ptime]) VALUES (student_id,Student_Name,Activities,pDate,pDay,Ptime )"
'Dim Stradd12 As String = "INSERT INTO `tbl_student_attendence` ([student_id]) VALUES (student_id )"
Dim cm12 As OleDbCommand = New OleDbCommand(Stradd12, DBconnection)
cm12.Parameters.AddWithValue("student_id", CType(ListView1.Items(x).SubItems(0).Text, Integer))
cm12.Parameters.AddWithValue("Student_Name", CType(ListView1.Items(x).SubItems(1).Text, String))
cm12.Parameters.AddWithValue("Activities", CType(ListView1.Items(x).SubItems(2).Text, String))
cm12.Parameters.AddWithValue("pDate", CType(DateTimePicker1.Value, String))
cm12.Parameters.AddWithValue("pDay", CType(ComboBox1.Text, String))
cm12.Parameters.AddWithValue("Ptime", CType(ListView1.Items(x).SubItems(3).Text, String))
'cm12.Parameters.AddWithValue("Registration_no", CType(TextBox1.Text, Integer))
cm12.ExecuteNonQuery()
cm12.Parameters.Clear()
End If
' Next
Next
MsgBox("Attendence Updated Successfully.")
End Sub

flagging vb.net with sql

please help in flagging
using vb.net and sql server
i want the deleted value (1) will be highlight with color cyan when the selected data in datagridview is double click
this is my code
Private Sub showme()
Dim i As Integer
For i = 0 To dgvDoctorsList.RowCount > -1
Dim remrks = dgvDoctorsList.Rows(i).Cells(6).Value
If remrks = "1" Then
dgvDoctorsList.Rows(i).DefaultCellStyle.BackColor = Color.Cyan
End If
Next
End Sub
Private Sub dgvDoctorsList_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDoctorsList.CellDoubleClick
If MessageBox.Show("Are you sure want to delete this data ?", "CONFIRMATION", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = Windows.Forms.DialogResult.Yes Then
Dim objCmd As New SqlCommand()
Using con As New SqlConnection("server=ACHACOSOFAMILY;database=jjasgh;integrated security=true")
objCmd.Connection = con
con.Open()
For Each objRow As DataGridViewRow In dgvDoctorsList.SelectedRows
objCmd.CommandText = "Update tbl_Doctor SET Remarks=1 where License_no=#license"
objCmd.Parameters.AddWithValue("#license", dgvDoctorsList.CurrentRow.Cells(0).Value)
objCmd.ExecuteNonQuery()
showme()
Next
End Using
End sub
thanks for consideration please help
thanks in advance
If your doubleclick event working good, then you have to do it in RowPrepaint event ..
Private Sub dgvDoctorsList_RowPrePaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles dgvDoctorsList.RowPrePaint
Dim x as Integer = e.RowIndex
If dgvDoctorsList.Rows(x).Cells("remarks").Value= 1 Then
dgvDoctorsList.Rows(x).DefaultCellStyle.BackColor = Color.Cyan
End If
End Sub

looping through all records on the database

i revised the code a little from a friend
but it only display the first record how will i able to manipulate to loop through all records
anyone who could give correct answer in code will receive bounty thanks
Note: DisplayOfficeEquipmentList() is a sub that displays data on the database to the textboxes and comboboxes
Public Sub DisplayOfficeEquipmentList()
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim dt As New DataTable
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentProfile", sqlconn)
da.Fill(dt)
cmbCategory.Text = dt.Rows(0)("OE_Category").ToString()
cmbSubCategory.Text = dt.Rows(0)("OE_SubCategory").ToString()
txtOEID.Text = dt.Rows(0)("OE_ID").ToString()
txtName.Text = dt.Rows(0)("OE_Name").ToString()
txtUser.Text = dt.Rows(0)("OE_User").ToString()
cmbBrand.Text = dt.Rows(0)("OE_Brand").ToString()
cmbModel.Text = dt.Rows(0)("OE_Model").ToString()
txtSpecs.Text = dt.Rows(0)("OE_Specs").ToString()
txtSerialNo.Text = dt.Rows(0)("OE_SerialNo").ToString()
txtPropertyNo.Text = dt.Rows(0)("OE_PropertyNo").ToString()
txtMacAddress.Text = dt.Rows(0)("OE_MacAddress").ToString()
txtStaticIP.Text = dt.Rows(0)("OE_Static_IP").ToString()
txtVendor.Text = dt.Rows(0)("OE_Vendor").ToString()
dtpPurchaseDate.Text = dt.Rows(0)("OE_PurchaseDate").ToString()
txtWarrantyStatus.Text = dt.Rows(0)("OE_WarrantyStatus").ToString()
txtWarrantyInclusiveYear.Text = dt.Rows(0)("OE_WarrantyInclusiveYear").ToString()
txtStatus.Text = dt.Rows(0)("OE_Status").ToString()
cmbDeptCode.Text = dt.Rows(0)("OE_Dept_Code").ToString()
cmbLocationCode.Text = dt.Rows(0)("OE_Location_Code").ToString()
txtRemarks.Text = dt.Rows(0)("OE_Remarks").ToString()
sqlconn.Close()
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click
End Sub
You have to loop the lines, you are getting the values of the row at index 0( Just one row).
Use foreach:
foreach (System.Data.DataRow row in dt.Rows)
{
//Get values of row
}
EDIT: In vb.net it would be something like this:
For Each filarow As DataRow In dt.Rows
Dim OE_ID As String = filarow("OE_ID").ToString
Dim txtName As String = filarow("OE_NAME").ToString
Next
By the way, it seems you are filling textboxes, so the values will change at the next loop. Maybe you should use another control like a ListBox
You need to separate the logic that retrieve data from the logic that shows that data.
First add a method that load your datatable
Private Function LoadData() as DataTable
Using sqlconn = New SqlClient.SqlConnection("server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true")
Dim dt As New DataTable
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentProfile", sqlconn)
da.Fill(dt)
return dt
End Using
End Function
Then in the buttons click pass the datatable and the rownumber to display to the DisplayOfficeEquipmentList
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
if currentRow + 1 >= dt.Rows.Count Then
Return
End if
currentRow = currentRow + 1
DisplayOfficeEquipmentList(dt, currentRow)
End Sub
Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
if currentRow - 1 < 0 Then
Return
End if
currentRow = currentRow - 1
DisplayOfficeEquipmentList(dt, currentRow)
End Sub
and in the DisplayOfficeEquipmentList refer to the row passed by the buttons click
Public Sub DisplayOfficeEquipmentList(ByRef dt as DataTable, ByVal rowNum as INteger)
Dim row as DataRow
row = dt.Rows(rowNum)
cmbCategory.Text = row("OE_Category").ToString()
cmbSubCategory.Text = row("OE_SubCategory").ToString()
....
End Sub
For this to work, you need to call the LoadData somewhere when you show your form (Load event?) and you should set the currentRow as a form global level variable