how do I refresh the textbox/datatable to re-run this command? - vb.net

This piece of code grabs a customers hire record using their hire ID and displays their details in multiple textboxes. It all works fine and well, however, I can only run it once. If I type in another customers hire record ID it just displays the first customers details that were materialised, which I assume is because the datatable has been populated and not refreshed based on the new hire record ID I've entered.
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim hirerecord1 As Integer = TextBox13.Text
Dim cmd2 As New SqlCommand("SELECT * FROM HireItemRecord WHERE HireRecord_Id = " & hirerecord1, cnn)
Dim sqlDa As New SqlDataAdapter(cmd2)
sqlDa.Fill(dt1)
If dt1.Rows.Count > 0 Then
TextBox14.Text = dt1.Rows(0)("RentalItem_Id").ToString()
TextBox15.Text = dt1.Rows(0)("HireRecord_Id").ToString()
TextBox45.Text = dt1.Rows(0)("HireItemBeginDate").ToString()
End If
cnn.Close()
End Sub
I'm not quite sure what to do to fix this...
Also, I'm having a similar problem with this..
Private Sub TextBox46_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox46.TextChanged
Dim keywords2 As String = TextBox46.Text
ds1.Tables("PersonDetails").DefaultView.RowFilter = "Last_Name like '%" & keywords2 & "%' "
End Sub
With this I can search a column of a datagridview for a match. It works all fine and well, until I insert a new record into the database at which point I refresh the datagridview to display the newly added record. After I do this, I can no longer search using the textbox. Once again, I'm not quite sure what to do to fix this issue.
Thank you very much for your help.

You're closing your connection at the end of the Button6_Click method and I can't see where it gets opened again. That would fit with your symptoms of the method only running successfully once. Have you tried to step through the code to see where it fails the second time?

Related

How to use DataGridView and a button to delete a SQL entry in my DataGridView

So I've got my SQL connection setup and working and it pulls and binds the data to the datagridview. I have an update button that pushes the edited data back to the SQL server.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
'Delete Current Cell Data
Dim deleteCmd As String = "Delete FROM Contacts WHERE au_id = #Id;"
Dim myCommand As SqlCommand = New SqlCommand(deleteCmd)
myCommand.Parameters.Add(New SqlParameter("#Id", SqlDbType.VarChar, 11))
'Start the SqlCommand "#Id" parameter to the ID of the row that was clicked.
myCommand.Parameters("#Id").Value = DataGridView1.SelectedCells
Now I am currently working on getting a delete button to function. Basically I need it to Delete the row of data that is currently selected.
Private Sub DeleteButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DeleteButton.Click
If DataGridView1.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
DataGridView1.Rows.Remove(DataGridView1.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
This is what I came up with! I was going about it all wrong attempting to do it via SQL queries. Just needed to do it locally and then use my update button to finish the changes. Which will probably be safer given that end users are end users.

how to update, insert records through datagridview to sql using data adapter or other method in vb.net

hello best programmers in the world i need your expert advise and assistance with regards to my project.
I am trying to insert and update my table through datagridview by clicking a command button,
i have my datagridview properties set to editmode : editprogrammatically,
here's the code, of where i pulled up my datagridview content:
Public Sub loaddgvfrm3()
cmdconn = New SqlConnection
cmd = New SqlCommand
cmdconn.ConnectionString = sqlstr
cmdconn.Open()
cmd.Connection = cmdconn
cmd.CommandText = "select period, VOUCH_AMT, INDIVIDUAL_AMT, check_no, D_MAILED, DIR_NO from tobee.EBD_BILLHISTORY where CLAIM_NO like '" + txtClaimno.Text + "'"
Dim dt As New DataTable
da = New SqlDataAdapter
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
Me.DataGridView2.DataSource = dt
cmdconn.Close()
End Sub
now i have my command buttons here
here's the add button: (im prefering to add a row within the selected table)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
End Sub
here's the Edit button:
Private Sub btnEditmain_Click(sender As Object, e As EventArgs) Handles btnEditmain.Click
''Form1.ShowDialog()
'DataGridView2.AllowUserToAddRows = True
''DataGridView2.BeginEdit(True)
'btnSave.Enabled = True
End Sub
and here's the save button that should save all changes that i have done,
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim connstr As String = "server=midtelephone\sqlexpress; database=testdb; user= sa; password=sa;"
End Sub
i left command button contents empty because i need to create a new method of inserting, updating the row. because the one that i have earlier was a fail, although it inserts the data in the sql, but not in its appropriate row, take a look at here: Data inserted from datagridview not updated in SQL Server , instead it creates another row which is not connected with '" + txtClaimno.Text + "'" (stated from above) so what happens is that it stacks a new row with no connected owner from another table(claim_no < this claim_no is connected from another table as a fk in the database but a primary key in (billhistory table))
can you pls help me get rid of this problem as i am having a hard time moving to the next phase of our project? im just a high school student, so pls bear with me :) i'll appreciate if u give comments / answers regarding my question :) thanks in adv.
my mentor advised me to use data adapter accept changes stuff, but i don't know how to implement such stuffs. pls help me thank you :)
Use Event to get data from gridview on cellConttent Click and these values to a query or Stored procedure.
private void grdCampaignStats_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//I want to get value of SomeColumn of grid view having datatype String
string SomeVariabel = grd["CoulmnNameinGRID", e.RowIndex].Value.ToString();
// Make it according to Vb it is C# code
}

VB forms run time error, Adding columns to a Data Table

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim itemno As String
Dim quantity, count As Integer
count = count + 1
itemno = TextBox5.Text
Quantity = TextBox6.Text
sql = ("SELECT ItemNo ,DishName, DishPrice FROM tblMenuInfo WHERE ItemNo = """ & itemno & """")
da = New OleDb.OleDbDataAdapter(sql, Conn)
da.Fill(dsorder, "OrderInfo")
If count = 1 Then
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
dsorder.Tables("OrderInfo").Columns.Add("Sub total")
End If
DataGridView1.DataSource = dsorder.Tables("OrderInfo")
DataGridView1.AutoResizeColumns()
End Sub
Hi, I'm currently doing a ordering system project in school and am fairly new with VB forms
i have an access table called tblMenuInfo with the columns ItemNo, DishName, DishPrice.
I'm trying to add a column to my data table called Sub Total and Quantity. But I get the following error message
{"A column named 'Quantity' already belongs to this DataTable."}
(Sorry I couldn't provide a print screen, I'm on a school computer)
My program only crashes on the second click.
Thanks In advance!
After your first click the datatable contains following columns
ItemNo|Dishname|Dishprice|Total|Quantity
If you click the second time, your datatable still contains those columns.
ItemNo|Dishname|Dishprice|Total|Quantity
When the code reaches the following point:
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
The compiler says: "Hey i can't add that column! That column is already present in the datatable"
What you actually need to do: is check if the column is already present or clear the datatable of that dataset
Solution 1: Clear datatable after click
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim itemno As String
Dim quantity, count As Integer
dsorder.Tables.Clear()
Note on solution 1: All data contained by the ds will be lost
Solution 2: Check if the column is present
'Check if datatable exists
If (dsorder.Tables("OrderInfo") IsNot Nothing) Then
'Check if column exists
If Not dsorder.Tables("OrderInfo").Columns.Contains("Quantity") Then
dsorder.Tables("OrderInfo").Columns.Add("Quantity")
dsorder.Tables("OrderInfo").Columns.Add("Sub total")
End If
End If

already an open DataReader associated with this Command when am chekcing with invalid data

Private Sub txt_sname_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_sname.GotFocus
Dim fcs As String
fcs = "select fname,dept from nstudent where stid = '" & txt_sid.Text & "'"
scmd1 = New SqlCommand(fcs, con)
dr1 = scmd1.ExecuteReader
If dr1.HasRows Then
Do While (dr1.Read)
txt_sname.Text = dr1.Item(0)
cmb_dept.Text = dr1.Item(1)
Loop
Else
MsgBox("Not Found")
End If
scmd1.Dispose()
If Not dr1.IsClosed Then dr1.Close()
End Sub
The above code for data from database and pass to textbox. When am running the program and checking with data which already present in database, it working properly. but checking with some other data(which not present in db)following error is occurring and exiting.
error:
"There is already an open DataReader associated with this Command which must be closed first."
pls help me..
Some observations:
Instead of using a global command object, use a local one. Especially since you are creating a new command anyway. And it looks like this is true of the dr1 as well.
You are not preventing SQL injection, so someone can type text in txt_sid that causes security issues by deleting data, dropping tables, or getting access to other data in the database.
You are looping and setting the same variables multiple times. If there is only going to be one record, don't bother looping.
Wrap the entire thing around a try/catch
Private Sub txt_sname_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_sname.GotFocus
Dim cmd1 As SqlCommand = New SqlCommand(fcs, "select fname,dept from nstudent where stid = #stid")
cmd1.Parameters.Parameters.AddWithValue("#stid", txt_sid.Text)
Dim studentReader as SqlDataReader
Try
studentReader = scmd1.ExecuteReader
If studentReader.Read Then
txt_sname.Text = studentReader.Item(0)
cmb_dept.Text = studentReader.Item(1)
Else
MsgBox("Not Found")
End If
Finally
studentReader.Close()
cmd1.Dispose()
End Try
End Sub
Finally, I think you might want to actually do this when txt_sid changes, not when txt_sname gets focus.

datagridview combobox

I have a datagridview containing 1st column (combobox), 2nd and 3rd column is textbox. The combobox was filled-up using datatable. My problem is on loading form, I will get a records from my database and set the value of my combobox base on those records. So if I have 5 records from my database then I should have 5 rows containing combobox in my datagridview.
Any suggestion would greatly appreciated
I tried the code below but there's an error saying "the following exception occured in the datagridview...." but it will display correctly, but if I click in any cell that error always appear.
Private Sub frmEditIngredientManagement_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sSQL = "SELECT * FROM fs_nutrient"
ReadSQL(sSQL)
Dim dtNutrient As New DataTable
dtNutrient.Load(reader)
dgvCbxIngredientList.DataSource = dtNutrient
dgvCbxIngredientList.DisplayMember = "ndb_no"
dgvCbxIngredientList.ValueMember = "nutrient_id"
sSQL = "SELECT * FROM fs_ingredient_management_nutrient INNER JOIN fs_nutrient ON fs_ingredient_management_nutrient.nutrient_id = fs_nutrient.nutrient_id WHERE ingredient_management_id = " & intIngredientManagementId & " "
ReadSQL(sSQL)
If reader.HasRows Then
While reader.Read
Dim row As String() = New String() {reader("ndb_no"), "dd", "vv"}
dgvNutrient.Rows.Add(row)
End While
End If
End Sub
Completely new answer. Found a way around the error:
Answer was found in MSDN datagridviewcomboboxcolumn helpfile
Add this routine to "report errors" and forget about the error you get:
Private Sub dgvNutrient_DataError(ByVal sender As Object, ByVal e As DataGridViewDataErrorEventArgs) Handles dgvNutrient.DataError
'MessageBox.Show("Error happened " & e.Context.ToString())
End Sub