I have two tables in my Access Database where I used to store the information of Item In and Item Out. I am displaying those data from both table in a DataGridView using a DataSet. Item In displayed in DataGridView1 and Item Out displayed in DataGridView2.
Here is my Module Function
Function to display Item In
Public Sub load_item_in()
ds_i.Reset()
Dim i_sql As String
Dim conn_i As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = access-database-file-dir")
i_sql = "SELECT * FROM item_in"
da_i = New OleDb.OleDbDataAdapter(i_sql, conn_i)
da_i.Fill(ds_i, "InventoryIn")
Form6.DataGridView1.DataSource = ds_i.Tables("InventoryIn")
Form6.DataGridView1.ReadOnly = True
End Sub
Function to display Item Out
Public Sub load_item_out()
ds_i.Reset()
Dim i_sql As String
Dim conn_i As New OleDb.OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = access-database-file-dir")
i_sql = "SELECT * FROM item_out"
da_i = New OleDb.OleDbDataAdapter(i_sql, conn_i)
da_i.Fill(ds_i, "InventoryOut")
Form6.DataGridView2.DataSource = ds_i.Tables("InventoryOut")
Form6.DataGridView2.ReadOnly = True
End Sub
Calling out the function when button clicked
myModule.load_item_in()
myModule.load_item_out()
As you can see there, I am displaying two different DataGridView in a same form.
The problem I faced here is, I have table displayed in the DataGridView1 but no data displayed there. My DataGridView2 is able to display all data. So I am wondering either the system get confused of which data to called out because unable to display data at DataGridView1
Looks like you're using the same DataSet in both functions and resetting it before each call.
The ds_i.Reset() method in load_item_out() is clearing the data that the first method load_item_in() retrieved. Remove your DataSet "reset" and add a DataTable clear before filling the DataAdapter.
It has been awhile since I have worked in VB - though you have these in two separate sub routines I do not see where you are closing the connection to the DB. Each sub should have a connection start and a connection stop.
This is a datagridview example from a project I did in school - the main form had 4 dgv's and each had this code block with a different select statement. They all ran in the same sub but had their own try calls -
Private Sub Sponsor_Load()
'-----gridviewB----++++++
'required try catch +++++
Try
'declare variables
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
'database opened
If OpenDatabaseConnectionSQLServer() = False Then
'database fail - alert user and exit program
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
'select statement
strSelect = "SELECT * FROM TSponsors WHERE intSponsorID= " & cboSponsor.SelectedValue.ToString
'pull records from sourcetable
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
'load data table
dt.Load(drSourceTable)
'populate the datagrid view
dgvSponsor.DataSource = dt
'close source table
drSourceTable.Close()
'close db connection
CloseDatabaseConnection()
'requried try catch - +++++
Catch excError As Exception
'display error message
MessageBox.Show(excError.Message)
End Try
End Sub
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have three SQL tables: TGolfers, TEventYears, and TGolferEventYears. TGolferEventYears is a table of which golfer played in which event. I have successfully populated an Event Years combo box (cboEventYears), now I am trying to populate a second Golfers combo box based on the golfers in the year selected. But for some reason, my SELECT statement is throwing the error: 'Object reference not set to an instance of an object.' I have no idea what that means, can anyone help? Code below, thanks.
'Load golfers combo box based on event year
Private Sub cboEventYears_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboEventYears.SelectedIndexChanged
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand 'Used for Select Statement
Dim drSourceTable As OleDb.OleDbDataReader 'Where data is retrieved to
Dim dt As DataTable = New DataTable 'Table we will load from our reader
'Open the DB
If OpenDatabaseConnectionSQLServer() = False Then
'If not, warn user
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
'Close form
Me.Close()
End If
'Build Select Statement
strSelect = "SELECT TGolfers.intGolferID, TGolfers.strLastName FROM TGolferEventYears JOIN TGolfers ON TGolferEventYears.intGolferID = TGolfers.intGolferID WHERE TGolferEventYears.intEventYearID = " & cboEventYears.SelectedValue.ToString
'Retrieve all records
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
'Load Table from Data Reader
dt.Load(drSourceTable)
'Add item to Combo Box. We need golferID to be associated
'with the last name in order to pull the rest of the data.
'Binding column name to the combo box display and value members.
cboGolfers.ValueMember = "TGolfers.intGolferID"
cboGolfers.DisplayMember = "TGolfers.strLastName"
cboGolfers.DataSource = dt
'Select first item in the list by default
If cboGolfers.Items.Count > 0 Then cboGolfers.SelectedIndex = -1
Catch excError As Exception
'Log and display error message
MessageBox.Show(excError.Message)
End Try
End Sub
most probably you are referencing a null value in your select statement, I would say that cboEventYears.SelectedValue.ToString is your culprit. Try your code again but with a constant instead of this and see if this fixes. And you can also try cboEventYears.text I have noticed it's usually the better option.
I have a problem with a DataGridView based application. After adding records to the grid, if I subsequently attempt to update or delete the new records I get the following respective errors.
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
Concurrency violation: the DeleteCommand affected 0 of the expected 1 records.
A save of the dataset is enforced in the RowValidated event.
Private Sub uxGrid_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles uxGrid.RowValidated
If IsDGVRowDirty(sender, e.RowIndex) Then
Save()
End If
End Sub
Private Sub Save()
Const procName As String = "Save"
Try
_Logger.SendLog(Me.Name & "." & procName & " - Saving alarm definition data.", NLog.LogLevel.Trace)
_myAlarmDefinitionMngr.Save(_myDataSet)
_Logger.SendLog(Me.Name & "." & procName & " - Alarm definition data has been saved.", NLog.LogLevel.Trace)
Catch ex As Exception
MsgBox("There was a problem whilst saving your changes. Please reload the form and try again. " & vbCrLf & vbCrLf & ex.Message, MsgBoxStyle.Critical)
_Logger.SendLog(ex.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, ex)
Finally
End Try
End Sub
The client app sits on top of a relatively simple 3-tier architectural design talking to an Oracle 11 back-end, in this case comprising the elements AlarmDefinitionManager.vb, AlarmDefinitionDB.vb, AlarmDefinition.vb.
Public Function Save(ByVal myDataSet As DataSet) As Integer
Dim myOda As OracleDataAdapter
Dim myConnection As New OracleConnection
Dim myCommand As OracleCommand = Nothing
Dim myDataAdapter As OracleDataAdapter
Dim myBuilder As OracleCommandBuilder
Dim sqlStatement As String
myConnection = New OracleConnection
myConnection.ConnectionString = _connectStr
sqlStatement = "SELECT ID, LEGENDID, STATUSID, STATUSTYPEID, DIGITALSET FROM P_TBL_ALARMDEF"
If myDataSet.HasChanges Then
Try
myOda = New OracleDataAdapter(sqlStatement, myConnection)
myBuilder = New OracleCommandBuilder(myOda)
myOda.SelectCommand = New OracleCommand(sqlStatement, myConnection)
myOda.Update(myDataSet, "AlarmDefinition")
myDataSet.AcceptChanges()
myConnection.Close()
Catch ex As Exception
Throw
Finally
myCommand = Nothing
myDataAdapter = Nothing
myBuilder = Nothing
CType(myConnection, IDisposable).Dispose()
End Try
End If
End Function
My understanding of the situation is that I need to refresh the datasource in the grid, such that it reflects the changes made. In order to achieve this I wish to refresh the grid by hooking the refresh process into an event in the datagridview. However none of the events which I have tried seem to work. With each event tried thus far, I have received errors to the effect that a refresh of the datasource is not permitted from within the event. On reflection this seems logical. Is there any event associated with the datagridview which I can use to force a refresh of the datasource?
You shouldn't try to save your dataset while validating the row.
do your changes to your dataset then set your datasource to null and reattach your datasource back to the grid to force a refresh.
I personally don't like making changes to the datagrid. I prefer to edit the row outside the datagrid and send an UPDATE cmd to SQL then refresh my grid. I get more control on the changes made to the grid.
Sorted my problem. Each row change is saved directly to the database within the RowValidated event.
I am trying to Load the form as
Dim f as New Form2
f.show()
The form is getting loaded but it doesnt show all the controls. I have two buttons and two text box. Both the buttons and one text box appears as transparent. The form appears like that till the current subroutine has ended.
Moreover, the form on loading shall display the text fetched from database and shall display the text (fetched again at equal interval from db) unless user explicitly closes the application. That logic also is in Form2_Load event.
How do I write the logic such that form2 displays properly and gets the text from db at regular interval.
I am creating a dictionary like application for healthcare domain. It works in two mode. One of the mode is ribbon mode, where a form is created (the form is marked as topmost) which should display the term and definition as long as application is alive. Hence you see an endless loop. Once user presses the close button or presses X, the application will close.
I was playing around with the code and moved it from Load even to shown event. However the issue persists.
Private Sub Form2_Shown(ByVal sender As Object, ByVal e As EventArgs) _
Handles MyBase.Shown
Dim myConnection As OleDbConnection = New OleDbConnection
Dim idSelected, queryGetWordDef, totalRows
Dim rowReturned, queryGetMaxID, provider, ipath, dataFile, connString As String
Dim dict() As String
Dim dr1 As OleDbDataReader
Dim dt As DataTable = New DataTable
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
ipath = Application.StartupPath
dataFile = ipath & "\Database\database1.mdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
queryGetMaxID = "SELECT ID FROM Table1"
myConnection.Open()
Dim cmd As OleDbCommand = New OleDbCommand(queryGetMaxID, myConnection)
Try
dr1 = cmd.ExecuteReader()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
dt.Load(dr1)
totalRows = dt.Rows.Count
While True
idSelected = dt.Rows.Item(CInt(totalRows * Rnd()) + 1)(0)
queryGetWordDef = "SELECT Word & ""#"" & Meaning FROM Table1 WHERE ID = " & CStr(idSelected)
cmd = New OleDbCommand(queryGetWordDef, myConnection)
Try
rowReturned = cmd.ExecuteScalar()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
dict = rowReturned.Split("#")
Me.txtBoxDefinition.Text = dict(1)
Me.txtBoxTerm.Text = dict(0)
Thread.Sleep(5000)
End While
End Sub
Picture of form attached for more clarity.
As mentioned, you have an infinite loop. The loop is entered before the form is completed being created.
To achieve what you are requesting you need to look at backgroundworker
You can use this in conjunction with the timer to trigger the backgrounderworker doWork() event.
The link also has an example of how to update the text on a form as well.
You have an endless loop in your Shown event handler. That code is executed on the UI thread and it never ends, so you can never do anything else on the UI thread.
Get rid of that loop altogether. If you want to do something every 5 seconds then use a Timer with an Interval of 5000.
I am able to add my records into my database without any problem, but I have trouble displaying it automatically into my datagridview.
In order for me to view my records in my datagridview, I need to close and restart the whole thing for it to appear. Is there any code that I've missed?
Private Sub btnAddEmp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddEmp.Click
Dim tranEmployee As SqlClient.SqlTransaction
sAdapter = New SqlDataAdapter(cmdEmployee)
Dim strID As String
Dim strName As String
Dim strPosition As String
Dim strContactNo As String
Dim strAddress As String
Dim strDOB As String
Dim strGender As String
Dim strSQL As String
conn.Open()
strID = mskEmployeeID.Text
strName = txtEmpName.Text
strPosition = cboEmpPosition.Text
strContactNo = mskEmpDOB.Text
strDOB = mskEmpDOB.Text
strAddress = txtEmpAddress.Text
If radEmpMale.Checked Then
strGender = "Male"
Else
strGender = "Female"
End If
strSQL = "INSERT INTO Users(userID,userName,userPosition,userGender,userDOB,userAddress)" & _
"VALUES(#ID,#NAME,#POSITION,#GENDER,#DOB,#ADDRESS)"
tranEmployee = conn.BeginTransaction()
With cmdEmployee
.Transaction = tranEmployee
.CommandText = strSQL
.Parameters.AddWithValue("#ID", strID)
.Parameters.AddWithValue("#NAME", strName)
.Parameters.AddWithValue("#POSITION", strPosition)
.Parameters.AddWithValue("#GENDER", strGender)
.Parameters.AddWithValue("#DOB", strDOB)
.Parameters.AddWithValue("#ADDRESS", strAddress)
.Connection = conn
End With
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
End Sub
The code you've shown will successfully add a record to the database, but it doesn't make any attempt to refresh anything in the UI. Where is the code which binds the grid to records in the database? That code needs to be run again after this code runs.
I'm assuming that code exists in some sort of initializer for the form. Perhaps some sort of load event? You'll want to move that grid-binding code into its own function and call it from both the load event and at the end of this click event, probably right after the line where you commit the transaction.
You need to call your select statement subroutine again. The statement where you pulled your information from the database.
Try
cmdEmployee.ExecuteNonQuery()
tranEmployee.Commit()
Catch ex As Exception
tranEmployee.Rollback()
MessageBox.Show(ex.Message)
Finally
conn.Close()
selectUsers()
End Try
I created an htmltable in .aspx.vb, because I have a lot of rows that come from database and they depend on the querystring. that part is fine. But when someone makes a change in one of the cells how do I save data back to database?
Code -
Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)
Now when someone changes the price in the textbox, how do I save it in database?
This is code for submit button -
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
sqlstr = "UPDATE ???"
sqlcmd = New SqlCommand(sqlstr, sqlcnn)
sqlcmd.ExecuteScalar()
End Sub
Please answer in detail.
I would suggest using the built in grid controls. Here is a walkthrough Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
. It might be better to start with Walkthrough: Basic Data Access in Web Pages.
If you choose to move forward with HTML then here is one way to do it based on what you provided. You can add an update button and try this code in that event:
'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = #Price WHERE ID = #ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("#Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("#ID", SqlDbType.Int)
connection.Open()
'Loop through the fields returned'
For Each Key As String In Request.Form.Keys
'Make sure you only process fields you want'
If Key.StartsWith("price") Then
'Pull the ID out of the field name by splitting on the underscore'
' then choosing the second item in the array'
Dim ID As String = Key.Split("_")(1)
'Update the paramaters for the update query'
Cmd.Parameters("#ID").Value = ID
Cmd.Parameters("#Price").Value = Request.Form(Key)
'Run the SQL to update the record'
Cmd.ExecuteNonQuery()
End If
Next
connection.Close()
Let me know if you need any additional assitance. If not, please mark this as the correct answer.