Refreshing a data grid view - vb.net

This looks like an easy fix but I can't figure this out. I'm trying to have button click event on a subForm (NewTournament), add a record to a database, and then to notify a data grid which lists the records from the same database automatically (the grid is listed on HomeForm).
I so for am able to update the database and call upon a new window. But I can't get it to refresh that datagrid for anything. I know I'm supposed to clear the datagrid, get changes, then refill the grid. But everytime I do this, the code is NOT updating. Furthermore, I can very well see that the record is being added.
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' Check the form for errors, if none exist.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd, cmd1 As OleDbCommand
Dim icount As Integer
Dim str, str1 As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\Paul Williams III\Documents\Visual Studio 2010\Projects\Everything OP Client\Everything OP Client\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
str1 = "select ##Identity"
icount = cmd.ExecuteNonQuery
cmd1 = New OleDbCommand(str1, cn)
Counter = CInt(cmd1.ExecuteScalar)
MessageBox.Show(Counter & " was the last inserted id")
'displays number of records inserted
HomeForm.MasterDataSet.Clear()
HomeForm.MasterDataSet.GetChanges()
HomeForm.TournamentsTableAdapter.Fill(HomeForm.MasterDataSet.Tournaments)
HomeForm.DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow
n.TournID = Counter
n.Show(HomeForm)
End Sub

The best approach is to add the record to the DataSource of the DataGrid. The DataGrid will automatically update. In this case its likely to be somehting like
HomeForm.MasterDataSet.Tournaments.AddTournamentsRow( CInt(SanctioningIDTxt.Text) , _
Trim(TournamentNameTxt.Text) , _
"1" , _
EventDateTimePck.Value, _
TableFirstNumberNo.Value, _
GameList.SelectedIndex, _
FormatList.SelectedIndex, _
Convert.ToInt32(ToIDTxt.Text) )
As an aside you might want to consider using parameterized queries for your Insert statement

This is my answer I hope you like it. On my project I have a switchboard and in that switchboard it contains the data grid view for my data. Before it only refresh it self when the user used the query and it will refresh it self. I taught about it how to do it different. So I used this technique the timer refresh effect. How does it work I put a timer and in the timer I copy and paste this code from the form load.
Me.ADDRESS_TICKETTableAdapter.Fill(Me.Database1DataSet.ADDRESS_TICKET)
And in the settings of the timer i turn it on and every 9 seconds it reloads the data you can change it that it reloads every 1 second if you like depends how many records it comes in. I hope this answer help you in anyway. It work for me.

Related

How to insert or update database using a datagridview?

I have a datagridview whereby i want to insert data into database.If the data exist then it should be updated.And also the last column of the datagridview when i click it should change from datagridviewtextbox to datagridviewcomboboxcell.
how can i insert or update data into the datagridview and when i click the last column it should change from datagridviewtextbox to datagridviewcomboboxcell
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each row As DataGridViewRow In DataGridView1.SelectedRows
If Not row.IsNewRow Then
sqlSTR = "SELECT ID, Code, SubjectName, Abbrev, Category FROM TBL_SubjectReg WHERE (Code = '" & row.Cells(0).Value & "')"
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
sqlSTR = "UPDATE TBL_SubjectReg SET Code ='" & row.Cells(0).Value & "', SubjectName ='" & row.Cells(1).Value & "', Abbrev ='" & row.Cells(2).Value & "', Category ='" & row.Cells(3).Value & "' WHERE (Code = '" & row.Cells(0).Value & "')"
ExecuteSQLQuery(sqlSTR)
MsgBox("Record updated successfully", MsgBoxStyle.Information, "Update")
Exit Sub
Else
sqlSTR = "INSERT INTO TBL_SubjectReg (Code, SubjectName, Abbrev, Category) VALUES ('" & row.Cells(0).Value & "','" & row.Cells(1).Value & "','" & row.Cells(2).Value & "','" & row.Cells(3).Value & "')"
ExecuteSQLQuery(sqlSTR)
'MsgBox("Record saved successfully", MsgBoxStyle.Information, "Record")
'Exit Sub
End If
End If
Next
End Sub
I think you should throw all that code away and start again with:
add a new DataSet type item to your project
open the DataSet by double clicking
right click on the design surface and choose New TableAdapter
pick a conncetionstring or create a connection and store it in the app settings, put a query of SELECT * FROM tbl_SubjectReg where Code = #code into the wizard, call the query FillByCode/GetDataByCode
finish the wizard, save the dataset
open the Data Sources window (view menu, other windows)
expand the nodes in the datasources window, drag the tbl_SubjectGrid node onto the form
a toolstrip with a textbox and search button appear, for you to type the code in. a datagrid appears, already properly bound to the dataset/datatable through a binding source. a tableadapter appears, and code that uses it to fill the grid is written
Run the project; put a code in the box, click the button, edit the data, click the floppy disk - it is saved. Add a new row; save it too
Work from this as a base; it's taken ab out 1 minute to create something that is miles better than the code you've already got there (for reasons like: resistant to sql injection, properly uses MVC concepts to separate data from presentation, it works...)

Checking rows and columns in datagridview if has no changes vb.net

How to check in Datagridview if there is no changes then prompt the user of no changes in my datagridview. I want to do this in my Update button to check first if there is no changes prompt msgbox then exit sub. how to do that? Lets say data from database already loaded to datagridview.
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
'this line is what I want for checking will happen if there is no changes in data happens in datagridview
Dim row, id, dgvUnits As Integer
Dim dgvYearLevel, dgvSemester, dgvCNo, dgvCDescription As String
'Declared this variable to get value event click on dgv
row = DataGridView1.CurrentRow.Index
id = DataGridView1(6, row).Value
dgvYearLevel = DataGridView1(1, row).Value
dgvSemester = DataGridView1(2, row).Value
dgvCNo = DataGridView1(3, row).Value
dgvCDescription = DataGridView1(4, row).Value
dgvUnits = DataGridView1(5, row).Value
Try
con.Open()
With cmd
.Connection = con
.CommandText = "UPDATE tblcurriculumcourses SET YearLevel='" & dgvYearLevel & "', Semester='" & dgvSemester & "', CourseNo='" & dgvCNo & "', CourseDes='" & dgvCDescription & "', Units='" & dgvUnits & "' where PrimaryDummy='" & id & "'"
End With
cmd.ExecuteNonQuery()
MsgBox("Data Has Been Successfully Update!")
Catch ex As Exception
MsgBox("Error when updating data")
End Try
I don't have a legitimate answer, but I got an idea. Maybe, you can dim one of the rows in the DataGridView as an array or string, and later, on the button, you can do something like
If DataGridView1(1, row).Value = TheArrayOrString Then
'This is what you want it to do. Example:
MsgBox("Your table is the same!")
Maybe, try something like that, also, you'd have to select all the rows for the DataGridView! What it is doing is once you make all the rows in a DataGridView an ArrayList, you can test if it hasn't changed or not. So the 'If DataGridView1(1, row).Valie = TheArrayOrString' is testing if the DataGridView1 table has had the same contents over a period of time. The 'MsgBox("Your table is the same!")' is self explantory. Hope this helps spread your imagination! Have fun! :)

How to get the ID of the most recently inserted Access record? [duplicate]

I have the following set of code for a Sub program. It's inserting a row into a MSAccess Database using data provided in the containing form. What I would like to do is grab the ID number of this added record so that it can be set for a property of a window that is invoked when successfully added. I tried looking this up but I get something about ##IDENTITY but it's using an entirely different way of connecting.
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' TODO: Check the form for errors, or blank values.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(Str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow ' Open a new Tournament window if everything is successful
n.TournID = Counter '<< This should be set to the ID of the most recently inserted row
n.Show(HomeForm)'Invoke the form and assign "HomeForm" as it's parent.
End Sub
Assuming you have an auto increment column in the Tournaments table, you can do a "SELECT ##IDENTITY" to get the id of the last inserted record.
BTW, is the SanctioningIDTxt.Text unique? If so, can't you use that?

Can someone assist me in getting data to display in a DataGridView vb.net?

I didnt have much luck when I posted about this when I was programming this application a different way, so I redid the program using DataAdapter instead of the TableAdapter method.
I need help getting data to display inside the DataGridView tool in vb.net Im not sure what i'm doing wrong here... The data displays in the listbox just fine. but will not display in the DataGridView tool. The DataGridView will display the length of the string. Unsure why... See my code below. (BTW, I created the listbox just for testing purposes and dont want to use that)
What the program does: A user places a checkmark on each house project (ex: cement work) and the project gets the list of tools required for the selected project(s). The project names are in checkboxes and checkChanged event assings the text to the variable "ProjectName" in the SQL select statement.
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim connection As OleDbConnection
Dim cmdString As String = "Select Distinct ToolName,Notes From Tools Where ProjectName = '" & carpentry & "' or ProjectName = '" & cementWork & "' Or ProjectName= '" & dryWall & "' Or ProjectName = '" & electrical _
& "' Or ProjectName = '" & HVAC & "' Or ProjectName = '" & laminateFlooring & "' Or ProjectName = '" & painting & "' Or ProjectName = '" & plumbing _
& "' Or ProjectName = '" & texture & "' Or ProjectName = '" & tileWork & "' Or ProjectName = '" & vinylFlooring & "'"
connection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=SaintEnterprises.mdb")
Dim adapter As New OleDbDataAdapter(cmdString, connection)
Dim tools As New DataSet
connection.Open()
adapter.Fill(tools)
Dim toolslist As New List(Of String)
ListBox1.Items.Clear()
For Each row As DataRow In tools.Tables(0).Rows
Dim s As String = row("toolname").ToString
'toolslist.Add(row("toolName").ToString) 'Does same thing as line toollist.add(s) below
toolslist.Add(s.ToString) 'add to List
ListBox1.Items.Add(s.ToString) 'Displays the type of tools based on the query.
Next
ToolsDataGridView.DataSource = toolslist 'displays the length (Total # of letters) of each toolname'
End Sub
Although I probably wont go back to doing it using Table adapter, if you'd like To see my way of programming this application using TableAdapter, see this link.
I think you need a DataTable to fill your DataGridView. Convert you DataSet-Rows to a DataTable.
I've tried this and this works fine for me (assuming, your database connection is working).
Dim oData As New System.Data.DataTable
For Each oRow As System.Data.DataRow In tools.Tables(0).Rows
oData.ImportRow(oRow)
Next
ToolsDataGridView.DataSource = oData

Why is ListView not refreshing?

Hi I am inserting into a table then reading everything back into a ListView When I re-open the program I see the data I just saved in my ListView, but this record is not showing in my ListView at the time of saving (although it is saved in the table).
I am using
listView.Update()
as well as
listView.Refresh()
but it does not seem to work. I am just using a SELECT query to read data off the datareader and store it in my listView as follows (which is working properly)
The only problem is that the listView is not refreshing immediately, but it works when I close/open the program
here's the code I am using at the end of my Save method. basically these two methods get called
Private Sub SetColumns()
Dim lstpenalty As New ListView()
lstpenalty.Items.Clear()
lstpenalty.Visible = True
lstpenalty.Bounds = New Rectangle(New Point(390, 55), New Size(560, 379))
lstpenalty.Name = "lstpenalty"
lstpenalty.FullRowSelect = True
lstpenalty.View = View.Details
lstpenalty.GridLines = True
lstpenalty.Items.Clear()
lstpenalty.Columns.Add("a", 75)
lstpenalty.Columns.Add("b", 70)
lstpenalty.Columns.Add("c", 105)
lstpenalty.Columns.Add("d", 98)
lstpenalty.Columns.Add("e", 90)
lstpenalty.Columns.Add("f", 105)
Me.Controls.Add(lstpenalty)
LoadPenaltyList(lstpenalty)
End Sub
Private Sub LoadPenaltyList(ByRef listView As ListView)
Dim gDR As OracleDataReader
Dim cmd As New OracleCommand
Dim lstpenaltyview As New ListViewItem
Try
cnn.Connect_to_Oper_Agent()
cmd.Connection = cnn.cnn
listView.Items.Clear()
cmd.CommandText = " select a," & _
"b, " & _
"c, " & _
"d," & _
"e," & _
"f" & _
" FROM myTable" & _
" commit"
gDR = cmd.ExecuteReader()
While gDR.Read
lstpenaltyview = listView.Items.Add(Null_To_String(gDR("a")))
lstpenaltyview.SubItems.Add(gDR("b"))
lstpenaltyview.SubItems.Add(gDR("c"))
lstpenaltyview.SubItems.Add(gDR("d"))
lstpenaltyview.SubItems.Add(gDR("e"))
lstpenaltyview.SubItems.Add(gDR("f"))
End While
listView.Update()
Catch ex As Exception
MsgBox("There was an error... -> " & ex.ToString)
Finally
cmd.Dispose()
cnn.Close_Conn()
End Try
End Sub
Thanks for your help
It is worth looking at what methods do.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview_methods%28v=vs.71%29.aspx
Update : Causes the control to redraw the invalidated regions within its client area.
Refresh: Forces the control to invalidate its client area and immediately redraw itself and any child controls.
To update it using table info, first Clear the listview, then redo the process you used to initially populate it.
So I was creating the ListView dynamically. The issue was that it kept creating ListViews over each other (memory leak), and it always showed the previous one. I created a static viewList versus a dynamic one and the issue is resolved:D
Use
For Each i As Windows.Forms.ListViewItem In ListView1.Items
i.Remove()
Next
Instead of Clear