looping through all records on the database - sql

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

Related

DataGridView add row

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()

Runtime datatable update error

I have a datagridview with a checkbox column. When I click(check/Uncheck) on checkbox field as random, two other fields in corrensponding row should be added OR removed in a datatable (declared runtime).
So that I can do some procedures with data in the datatable.
For that I have declared a datatable as global.
Now the problem is, each time when I click on a checkbox, a simple mouse scrolling is required to update datatable, OR a click needed in the new datagridview which is showing values in the datatable.
My code given below,
global declaration: Public PaymentTable As DataTable
Private Sub ShowOrdersFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataBind()
Me.DGVOrders.RowsDefaultCellStyle.BackColor = Color.GhostWhite
Me.DGVOrders.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleGoldenrod
PaymentTable = New DataTable()
PaymentTable.Columns.Add("RowId", GetType(Integer))
PaymentTable.Columns.Add("Amount", GetType(Decimal))
End Sub
Private Sub DataBind()
DGVOrders.DataSource = Nothing
DGVOrders.Columns.Clear()
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "select * from VIEW_PAYMENTS_DUES_BYORDER where CustCode='" & CustCode & "' order by OrderNo DESC"
End With
da.SelectCommand = cmd
da.Fill(dt)
BindingSource1.DataSource = dt
DGVOrders.DataSource = BindingSource1
DGVOrders.ClearSelection()
con.Close()
DGVOrders.Columns(0).Visible = False
DGVOrders.Columns(1).HeaderText = "Order No"
DGVOrders.Columns(2).HeaderText = "Cust Code"
DGVOrders.Columns(3).HeaderText = "Name"
DGVOrders.Columns(4).HeaderText = "Order Date"
DGVOrders.Columns(5).HeaderText = "Order Price"
DGVOrders.Columns(6).HeaderText = "Total Payment"
DGVOrders.Columns(7).HeaderText = "Dues"
For i = 0 To DGVOrders.RowCount - 1
If DGVOrders.Rows(i).Cells(7).Value > 0 Then
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Red
Else
DGVOrders.Rows(i).Cells(7).Style.ForeColor = System.Drawing.Color.Green
End If
Next
' CHECK BOX
Dim colmnchk As New DataGridViewCheckBoxColumn
colmnchk.DataPropertyName = "chkSelect"
colmnchk.HeaderText = "SELECT"
colmnchk.Name = "chkSelect"
DGVOrders.Columns.Add(colmnchk)
For i = 0 To DGVOrders.RowCount - 1
Next
'CHECK BOX END
End Sub
Private Sub DGVOrders_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGVOrders.CellValueChanged
If DGVOrders.Columns(e.ColumnIndex).Name = "chkSelect" Then
Dim checkCell As DataGridViewCheckBoxCell = _
CType(DGVOrders.Rows(e.RowIndex).Cells("chkSelect"), _
DataGridViewCheckBoxCell)
If checkCell.Value = True Then
PaymentTable.Rows.Add(DGVOrders.Rows(e.RowIndex).Cells(0).Value, DGVOrders.Rows(e.RowIndex).Cells(7).Value)
Else
Dim toRemoveID As Integer = DGVOrders.Rows(e.RowIndex).Cells(0).Value
For i = 0 To PaymentTable.Rows.Count - 1
If PaymentTable.Rows(i).Item(0) = toRemoveID Then
PaymentTable.Rows(i).Delete()
Exit Sub
End If
Next
End If
DataGridView1.DataSource = PaymentTable
End If
End Sub
Can sombody to solve the issue, or is there any other good method if my code is wrong ?
Try using a different event like CellContentClick and testing for the ColumnIndex. The drawback with this is the event will fire whenever you click on any cell.
Private Sub DGVOrders_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGVOrders.CellContentClick
'Only interested in the CheckBox column
If e.ColumnIndex = colmnchk.Index Then
Debug.WriteLine("In DGVOrders_CellContentClick for the checkbox")
End If
End Sub

Searching In datagridview in Windows Application VB.NET

I have to filter datagridview using textbox.The code below I am using to fill gridview.getdata function of db class returns the datatable.
I am not using datasource property of gridview instead I am filing gridview using loop.
I can do searching using datasource property and dataview but i have not to fill datagridview directly from datasource property.
Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
If DTT.Rows.Count > 0 Then
For i As Integer = 0 To DTT.Rows.Count - 1
DataGridView1.Rows.Add()
DataGridView1.Rows(i).Cells("crime").Value = DTT.Rows(i).Item("crime") & ""
DataGridView1.Rows(i).Cells("actname").Value = DTT.Rows(i).Item("actname") & ""
DataGridView1.Rows(i).Cells("section").Value = DTT.Rows(i).Item("section") & ""
DataGridView1.Rows(i).Cells("description").Value = DTT.Rows(i).Item("description") & ""
Next
End If
End Sub
Use the WHERE statement in your SQL Query
"SELECT crime,actname,section,description from natureofcomplaint_women WHERE crime = " & txtSearch.text
(If you want to search on crime.)
Change to your needs.
Just repeat the datagrid fill you used above, but with an altereted SQL query each time you type/press the search button
I still think it's best to bind...
Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
Dim source1 as New BindingSource()
source1.DataSource = DTT
source1.Filter = "crime = '" & textboxtCrime.text & "'"
DataGrideView1.DataSource = source1
End Sub
Sub griddesgn()
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
DataGridView1.Columns.Add("crime", "crime")
DataGridView1.Columns.Add("actname", "actname")
DataGridView1.Columns.Add("section", "section")
DataGridView1.Columns.Add("description", "description")
End Sub
Private Sub TEST_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
griddesgn()
Dim DBOBJ As New db
Dim DTT As DataTable = DBOBJ.getdata("SELECT crime,actname,section,description from natureofcomplaint_women")
If DTT.Rows.Count > 0 Then
For i As Integer = 0 To DTT.Rows.Count - 1
If (DTT.Rows(i).Item("Crime").Contains(txtCrimeFilter.Text) AND & _
(DTT.Rows(i).Item("actname").Contains(txtActnameFilter.Text) AND & _
(DTT.Rows(i).Item("section").Contains(txtSectionFilter.Text) AND & _
(DTT.Rows(i).Item("description").Contains(txtDescriptionFilter.Text)
DataGridView1.Rows.Add()
DataGridView1.Rows(i).Cells("crime").Value = DTT.Rows(i).Item("crime") & ""
DataGridView1.Rows(i).Cells("actname").Value = DTT.Rows(i).Item("actname") & ""
DataGridView1.Rows(i).Cells("section").Value = DTT.Rows(i).Item("section") & ""
DataGridView1.Rows(i).Cells("description").Value = DTT.Rows(i).Item("description") & ""
End If
Next
End If
End Sub

Updating data in gridview using vb.net

First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database

How to get the value of DataGridView.SelectedRows().Cells() from different forms?

I have 2 forms and within each of the 2 forms there is a DataGridView(chatform and prodetail).
In the chatform I created a DataGridView which has a generated Button in each row.
Each Button when clicked will load a prodetail form and when in the prodetail form I want to get the value of the SelectedRow.Cell from the DataGridView in the originating chatform.
Code (chatform):
Public Sub loadtoDGV()
Dim sqlq As String = "SELECT * FROM chattbl"
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"))
End With
Next
conn.Close()
End Sub
Private Sub ChatForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loadtoDGV()
End Sub
Code (DataGridView1.CellContentClick):
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Prodetail.Show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
Code (prodetail):
Public Sub loadtoDGV2()
Dim i As Integer
i = ChatForm.DataGridView1.SelectedRows.Count
MsgBox(i)
Dim compareai As String = ChatForm.DataGridView1.SelectedRows(i).Cells(1).Value
Dim sqlq As String = "SELECT * FROM Chattbl WHERE Title =" & compareai & ""
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"), tbl.Rows(i)("ChatContent"))
End With
Next
conn.Close()
End Sub
Private Sub Prodetail_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
loadtoDGV2()
End Sub
What have I done wrong?
I tried to use MsgBox(i) i = SelectedRow(0) assuming it would show the data for first row, but DataGridView1 in prodetail does not load any data from the database.
I did not observe any errors, I just don't have a solution.
The first problem is you are calling the class instead of an instance. VB.NET will allow you to call an instance of the form as its name, but it will be the same instance across every use. I would not suggest doing this.
To start I would change this:
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Prodetail.Show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
To this:
Private Sub grdData_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim colName As String = DataGridView1.Columns(e.ColumnIndex).Name
If colName = "Detail" Then
Dim newDetailForm as new Proddetail(dataGridView1.Rows(e.RowIndex).Cells(1).Value)
newDetailForm.show()
MessageBox.Show(String.Format("You clicked the button in row {0} of the Detail column", e.RowIndex))
End If
End Sub
Then in the Proddetail class you need to add a constructor and a member like this:
Private SearchValue as String
Public Sub New(byval theSearchValue as string)
InitalizeComponent()
SearchValue = theSearchValue
End Sub
Then in your load routine:
Public Sub loadtoDGV2()
Dim sqlq As String = "SELECT * FROM Chattbl WHERE Title =" & SearchValue & ""
Dim sqlcmd As New SqlCommand
Dim sqladpt As New SqlDataAdapter
Dim tbl As New DataTable
With sqlcmd
.CommandText = sqlq
.Connection = conn
End With
With sqladpt
.SelectCommand = sqlcmd
.Fill(tbl)
End With
DataGridView1.Rows.Clear()
For i = 0 To tbl.Rows.Count - 1
With DataGridView1
.Rows.Add(tbl.Rows(i)("Username"), tbl.Rows(i)("Title"), tbl.Rows(i)("ChatDateTime"), tbl.Rows(i)("ChatContent"))
End With
Next
conn.Close()
End Sub
This should then display the details of the clicked row in a new instance of the Proddetail class.
I added a custom paramaterized constructor to the class that takes the value for the SQL query string. This way when you create a new instance of the form in your code, you can always pass in the search string that would lead to the details you want to view.