I have a form and I'm wondering is it possible to calculate a specific column in a datagridview and output it to a label with the use of a generate button? If yes how do I go about doing it?
Thanks
(this is how the datagridview is set up)
Private Sub refreshdata()
If Not cnn.State = ConnectionState.Open Then
'open connection
cnn.Open()
End If
'create new data and insert the data, Employee, Firstname, lastname, address etc.
Dim da As New OleDb.OleDbDataAdapter("SELECT employeeno as [EmployeeID], " & _
"firstname as [FirstName], lastname as [LastName], address as [Address], department as [Department], workinghours as [WorkingHours], datehired as [DateHired], contactnumber as [ContactNumber] " & _
"FROM employee ORDER BY EmployeeNo", cnn)
Dim dt As New DataTable
'fill data into datatable
da.Fill(dt)
'offer data to be placed in datagridview
Me.DataGridView1.DataSource = dt
'close connection
cnn.Close()
End Sub`enter code here`
I'm not sure what you want to do. If you want just column header in your textBox try this:
C#
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = dataGridView1.Columns["columnName"].HeaderText;
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
textBox1.Text = dataGridView1.Columns("columnName").HeaderText
End Sub
To place your output inside label simply change textBox1.Text to label1.Text. If you want all data written inside your cells of certain column try this:
C#
private void button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow)
break;
sb.Append(row.Cells["columnName"].Value + " ");
}
textBox1.Text = sb.ToString();
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
Dim sb As New StringBuilder()
For Each row As DataGridViewRow In dataGridView1.Rows
If row.IsNewRow Then
Exit For
End If
sb.Append(row.Cells("columnName").Value + " ")
Next
textBox1.Text = sb.ToString()
End Sub
By the way, column name is the column name in design when you right click your DataGridView > Edit columns under design, there should be a "Name" parameter. Hopefully this covers the answer for your question. Cheers!
EDIT:
Added total sum of column output in textBox solution:
C#
private void button1_Click(object sender, EventArgs e)
{
int sum = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow)
break;
int number;
if (int.TryParse(row.Cells["columnName"].Value.ToString(), out number))
sum += number;
}
textBox1.Text = sum.ToString();
}
VB
Private Sub button1_Click(sender As Object, e As EventArgs)
Dim sum As Integer = 0
For Each row As DataGridViewRow In dataGridView1.Rows
If row.IsNewRow Then
Exit For
End If
Dim number As Integer
If Integer.TryParse(row.Cells("columnName").Value.ToString(), number) Then
sum += number
End If
Next
textBox1.Text = sum.ToString()
End Sub
Related
How do i calculate the sum of datagridview row content from a specific column?
Suppose, this is my datagridview;
Name Score
John 35
Helen 34
James 30
Total 99
I want to calculate the sum of column "score" put it in the textbox.
Thanks for the help.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i,total As Integer
total = 0
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Try
connection.Open()
adapter.SelectCommand = New SqlCommand("SELECT * FROM your_DB_table", connection)
adapter.Fill(ds)
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
total = total + ds.Tables(0).Rows(i).Item(1)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
textbox1.text = total
End Sub
End Class
I think this will help you.
Something like this,
Dim sumOfScore As Integer = 0
For Each row As DataRow in *yourDataRow*
Dim score As Integer = CInt(row.Item("Score").ToString())
sumOfScore += score
Next
txtYourTextBox.Text = sumOfScore.ToString
I also got this code which solves my problem:
Private Sub GetSUMofUnits()
Dim total As Integer
For Each row As DataGridViewRow In dgvSubjectsEnrolled.Rows
total += row.Cells(4).Value
Next
txtUnits.Text = total
End Sub
I have connected my DataGridView to a database but I can't implement the search function.
The flow of the program would be when I click one column of the DataGridView and I type in the search box, I can only get results from that same column not the other columns beside it.
It should also search letter by letter so basically a TextChanged event.
This is how i would do it
First, to have two variable to store your original datatable from database, and also a string variable to store your selected dgv column headertext (which will be used to do the filter later on).
Private oriDataTable As New DataTable
Private columnToFilter As String = String.Empty
My test on some dummy data
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'dummy datatable
oriDataTable.Columns.Add(New DataColumn("ID"))
oriDataTable.Columns.Add(New DataColumn("FirstName"))
oriDataTable.Columns.Add(New DataColumn("LastName"))
For i = 0 To 5
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type1 " & i
dr.Item("LastName") = "ln type1 " & i
oriDataTable.Rows.Add(dr)
Next
For i = 6 To 10
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type2" & i
dr.Item("LastName") = "ln type2" & i
oriDataTable.Rows.Add(dr)
Next
'Since you already connected to database
'i assume that you could fill a datatable and bind to dgv
dgvToFilter.DataSource = oriDataTable
columnToFilter = "ID" 'Assign any default column name
End Sub
Then add a ColumnHeaderMouseClick event handler on your dgv, update the columnToFilter each time when user click on it.
Private Sub dgvToFilter_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvToFilter.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = dgvToFilter.Columns(e.ColumnIndex)
'Note:HeaderText must match with your datatable column name
columnToFilter = clickedColumn.HeaderText
lblHeaderSelected.Text = columnToFilter
End Sub
And lastly the TextChaged Event. Use the DataTable.Select method to filter the datatable and update the result, if any, to the dgv.
Private Sub txtFilterText_TextChanged(sender As Object, e As EventArgs) Handles txtFilterText.TextChanged
If txtFilterText.Text.Length <= 0 Then dgvToFilter.DataSource = oriDataTable
Dim filterString = String.Format("{0} LIKE '{1}%'", columnToFilter, txtFilterText.Text)
Dim dataRows As DataRow() = oriDataTable.Select(filterString)
'Choose what you wan to do if no row is found. I bind back the oriDataTable.
dgvToFilter.DataSource = If(dataRows.Count > 0, dataRows.CopyToDataTable(), oriDataTable)
End Sub
You can try this.
Private Sub txtUname_TextChanged(sender As Object, e As EventArgs) Handles txtUname.TextChanged
dtaAdap = New SqlDataAdapter("Select * from tbl_user where Fname like '%" & txtUname.Text & "%'" & vbCrLf &
" OR Lname like '%" & txtUname.Text & "%'", con)
dt = New DataTable
dtaAdap.Fill(dt)
DataGridView1.DataSource = dt
End Sub
The query in SQLAdapter goes a little something like this:
Select * from <tbl_name> where <firstparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
OR <secondparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
and so on depending on the number of fields you want to look at. Note: "con" is my SQLConnection.
This whole code snippet will fill your DatagridView with the result of the query everytime the user key in something on your searchtextbox.
Hi guys i've been working so far with my system and it's almost done, but there is one thing i can't solve yet(not unless if you help me out).
so here's my code:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
Try
editdgv()
Form2.Show()
DataGridView2.AllowUserToAddRows = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
here's the private sub editdgv
Private Sub editdgv()
Dim i = DataGridView2.CurrentRow.Index
With DataGridView2
Form2.txtPeriod.Text = IIf(IsDBNull(.Rows(i).Cells("period").Value), " ", .Rows(i).Cells("period").Value)
Form2.txtVouch.Text = IIf(IsDBNull(.Rows(i).Cells("vouch_amt").Value), " ", .Rows(i).Cells("vouch_amt").Value)
Form2.txtIndivAmt.Text = IIf(IsDBNull(.Rows(i).Cells("individual_amt").Value), " ", .Rows(i).Cells("individual_amt").Value)
Form2.txtCheckno.Text = IIf(IsDBNull(.Rows(i).Cells("check_no").Value), " ", .Rows(i).Cells("check_no").Value)
Form2.txtDmailed.Text = IIf(IsDBNull(.Rows(i).Cells("D_MAILED").Value), " ", .Rows(i).Cells("D_MAILED").Value)
Form2.txtDirno.Text = IIf(IsDBNull(.Rows(i).Cells("DIR_NO").Value), " ", .Rows(i).Cells("DIR_NO").Value)
Form2.txtYrlvl.Text = IIf(IsDBNull(.Rows(i).Cells("year_student").Value), " ", .Rows(i).Cells("year_student").Value)
Form2.txtUpdatedBy.Text = IIf(IsDBNull(.Rows(i).Cells("who_updated").Value), " ", .Rows(i).Cells("who_updated").Value)
End With
End Sub
i was able to pass the value of the selected rows in datagridview to another form(textbox)
all things are working fine from there..
Now what i wanna do is to update that selected datagridview which is now in my textbox(s).
through a button click.
now i'm stuck at saving changes that i've done in the textbox, so it will be updated on the database.
pls help me on how to update the selected row in datagridview in textbox via button click.
thanks!
Public Class Form2
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
End Sub
End Class
I have created this code in notepad. So, it might have some issue.
FORM 1
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
Try
Dim dt As DataTable = TryCast(DataGridView2.DataSource, DataTable)
Dim dr As DataRow = dt.Rows(DataGridView2.CurrentRow.Index)
Dim frm As New Form2
frm.dr = dr
frm.Show()
DataGridView2.AllowUserToAddRows = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
FORM 2
Public dr As DataRow = Nothing
Private Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
With dr
txtPeriod.Text = IIf(IsDBNull(.Item("period")), vbNullString, .Item("period").ToString)
txtVouch.Text = IIf(IsDBNull(.Item("vouch_amt")), vbNullString, .Item("vouch_amt").ToString)
txtIndivAmt.Text = IIf(IsDBNull(.Item("individual_amt")), vbNullString, .Item("individual_amt").ToString)
txtCheckno.Text = IIf(IsDBNull(.Item("check_no")), vbNullString, .Item("check_no").ToString)
txtDmailed.Text = IIf(IsDBNull(.Item("D_MAILED")), vbNullString, .Item("D_MAILED").ToString)
txtDirno.Text = IIf(IsDBNull(.Item("DIR_NO")), vbNullString, .Item("DIR_NO").ToString)
txtYrlvl.Text = IIf(IsDBNull(.Item("year_student")), vbNullString, .Item("year_student").ToString)
txtUpdatedBy.Text = IIf(IsDBNull(.Item("who_updated")), vbNullString, .Item("who_updated").ToString)
End With
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
With dr
.Item("period") = txtPeriod.Text
.Item("vouch_amt") = txtVouch.Text
.Item("individual_amt") = txtIndivAmt.Text
.Item("check_no") = txtCheckno.Text
.Item("D_MAILED") = txtDmailed.Text
.Item("DIR_NO") = txtDirno.Text
.Item("year_student") = txtYrlvl.Text
.Item("who_updated") = txtUpdatedBy.Text
End With
dr.Table.AcceptChanges
End Sub
how i bind multiple data from sql to label if i choose an item in combo box that is from sql this is my code:
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
If cmboCourse.Text = "ADVANCED COMPUTER TECHNICIAN" Then
callMe()
ElseIf cmboCourse.Text = "AUTOELECTRICITY" Then
callMe()
ElseIf cmboCourse.Text = "AUTOMOTIVE" Then
callMe()
End If
End Sub
Private Sub callMe()
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "course")
lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
end sub
and this is my table
Course_Code Course
ACT ADVANCED COMPUTER TECHNICIAN
AE AUTOELECTRICITY
AM AUTOMOTIVE
it binds only one data, i want to bind many data in a particular column example i choose a course AUTOMOTIVE in combo box how does course_code of AUTOMOTIVE binds to label and if i choose AUTOELECTRICITY how does course_code of AUTOELECTRICITY binds to the same label
This is not tested, let me know if it doesn't work.
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
callMe(cmboCourse.Text)
End Sub
Private Sub callMe(ByVal course as String)
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course WHERE [Course]='" & course & "'"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "tbl_course")
'lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
If dataset1.Tables("tbl_course").Rows.Count > 0 Then
lbl.Text = dataset1.Tables("tbl_course").Rows(0)("Course_Code")
Else
MsgBox "Course [" & course & "] not found"
End If
End Sub
Please note that in your code, da.Fill(dataset1, "course") you specify the table to be 'course', while the select statement selects from 'tbl_course' table. I am assuming the latter is correct name.
Edit 1:
Bug fix
Edit 2:
Debugging
sc.Open()
Dim da As New SqlDataAdapter()
Dim dataset1 As New DataSet()
Dim sql As New SqlCommand("Select * from book where Title='" + cmbtit.Text + "'", sc)
da.SelectCommand = sql
da.SelectCommand.ExecuteNonQuery()
da.Fill(dataset1, "book")
If dataset1.Tables("book").Rows.Count > 0 Then
txtauthor.Text = dataset1.Tables("book").Rows(0)("Author")
Else
MsgBox("Author [" & cmbtit.Text & "] not found")
End If
sc.Close()
End Sub
I'm experiencing an issue where I use a data adapter to update and then refill a datatable. After calling the fill method, the row gets duplicated. One ID has the correct (new) ID and the other shows -1 for the ID. The code below works perfect and is the simpler form of what I want my more complex code to do. Cosider the following:
Imports WindowsApplication1.testDataSet
Imports WindowsApplication1.testDataSetTableAdapters
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim DA As New testTableAdapter
Dim DT As New testDataTable
DA.Fill(DT)
Dim NR As testRow = DT.Rows.Add
NR.SomeText = "Test"
Dim DA2 As New OleDbDataAdapter("SELECT * FROM test", _
DA.Connection.ConnectionString)
Dim CB As New OleDbCommandBuilder(DA2)
DA2.Update(DT)
DA.Fill(DT)
For Each R As testRow In DT.Rows
Debug.Print(R.ID)
Next
End Sub
End Class
The code above works perfect. They key column doesn't show -1, there are no duplicates. Now consider the code below from my application which causes a duplicate row with the key column resulting in -1 right after the last LoadLoadNumbers().
Dim AccountLoans As IEnumerable(Of LoanNumbersRow) = _
From L As LoanNumbersRow In LoanNumbers _
Select L Where L.AccountID = ID
If Not frmFindLoans.IsDisposed AndAlso _
frmFindLoans.DialogResult = Windows.Forms.DialogResult.OK Then
For Each L As LoanNumbersRow In AccountLoans
If (From R As DataGridViewRow In frmFindLoans.dgvLoans.Rows _
Select R Where R.Cells("LoanNumber").Value = L.LoanNumber).Count = 0 Then
If L.IsWhenDeletedNull Then
L.WhenDeleted = Now
L.DeletedBy = UserName()
End If
End If
Next
Dim NewLoan As LoanNumbersRow
Dim FindLoan As IEnumerable(Of LoanNumbersRow)
For Each R As DataGridViewRow In frmFindLoans.dgvLoans.Rows
FindLoan = From L As LoanNumbersRow In LoanNumbers.Rows _
Select L Where L.LoanNumber = R.Cells("LoanNumber").Value And _
L.AccountID = ID
If FindLoan.Count = 0 Then
NewLoan = LoanNumbers.Rows.Add
NewLoan.AccountID = Acc.AccountID
NewLoan.LoanNumber = R.Cells("LoanNumber").Value
NewLoan.LoanBusinessName = R.Cells("LoanBusiness").Value
NewLoan.LoanBorrower = R.Cells("LoanBorrower").Value
NewLoan.AddedBy = UserName()
NewLoan.WhenAdded = Now
End If
Next
Try
Dim CB As New OleDbCommandBuilder(LoanNumbersAdapter)
LoanNumbersAdapter.Update(LoanNumbers)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error saving loan number data")
Exit Sub
End Try
If Not LoadLoanNumbers() Then Exit Sub
End If
Other variables and such from a module:
Public LoanNumbersAdapter As OleDbDataAdapter
Public LoanNumbers As New LoanNumbersDataTable
Public Sub InitializeAdapters()
LoanNumbersAdapter = New OleDbDataAdapter( _
"SELECT * FROM LoanNumbers WHERE WhenDeleted IS NULL ORDER BY WhenAdded DESC", AccountingConn)
End Sub
Public Function LoadData(ByVal DA As OleDbDataAdapter, ByVal DT As DataTable) As Boolean
Try
DA.Fill(DT)
Return True
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error loading the " & DT.TableName & " table")
Return False
End Try
End Function
Public Function LoadLoanNumbers() As Boolean
Return LoadData(LoanNumbersAdapter, LoanNumbers)
End Function
Why does the simple test at the top work fine, but my actual application create the duplicate row with -1 on the key column? I suppose I could clear the datatable before filling after the update but wouldn't that bog it down once it starts becoming a large table?
*BTW: The DB is MS access and it's .NET 3.5
This is my duct tape solution :(
''' <summary>
''' Removes any rows where the ID/key column is less than zero
''' </summary>
<Extension()> Public Sub DeleteRelics(ByVal DT As DataTable)
If DT.PrimaryKey.Count = 0 Then Exit Sub
For Each R As DataRow In _
(From Rows As DataRow In DT.Rows _
Select Rows Where Rows(DT.PrimaryKey.First.ColumnName) < 0)
R.Delete()
Next
DT.AcceptChanges()
End Sub