Update Combobox on Save and Delete - vb.net

I have a bound combo box with employee profile names. I have two buttons: save and delete buttons.
When I edit a selected profile, I hit save and automatically the change is reflected in the bound combo box, but when I hit delete or create new profile, I have to close the app and when I open it I see the changes in the bound combo box.
The combobox.Refresh() no work
This is my code:
Private Sub deleteselectedprofile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_deleteprofile_oninsideprofiledittap1.Click
Dim mconn As New SqlConnection("Data Source=(local);Initial Catalog=epmapp_db;Integrated Security=true;")
Dim cmd As New SqlCommand
cmd.Connection = mconn
cmd.CommandType = CommandType.Text
cmd.CommandText = "delete GeneralInfo where RecordId= " + cbox_profiles.SelectedValue.ToString
Try
If MessageBox.Show("¿Está seguro de querer borrar este perfil?", _
"Delete", MessageBoxButtons.YesNo, _
MessageBoxIcon.Warning) = DialogResult.No Then
mconn.Close()
MsgBox("Operación Cancelada")
Else
mconn.Open()
cmd.ExecuteNonQuery()
MessageBox.Show("Su perfil se ha actualizado exitosamete")
Clear_Form_tap1()
disabling_controlstap1()
btn_newprofile_onload_tap1.Visible = True
btn_saveprofile_oninside_profileedit_tap1.Visible = False
btn_editprofile_oncboxselectiontap1.Visible = False
btn_cancelprofileedit_onprofileselectiontap1.Visible = False
btn_deleteprofile_oninsideprofiledittap1.Visible = False
cbox_profiles.Enabled = True
ErrorProvider1.Clear()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
mconn.Close()
End Try
End Sub
I set my combo box in the Design Tab using the...
Combo Box Task
Use Data Bound Items
Data Binding Mode
Data Source = GeneralInfoBindingDource
Display Member = Nombre
Value Member = RecordId
Selected Value = none
My save button code...
Private Sub btn_saveprofile_oninside_profileedit_tap1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_saveprofile_oninside_profileedit_tap1.Click
Me.Validate()
Me.GeneralInfoBindingSource.EndEdit()
Me.GeneralInfoTableAdapter.Update(Me.Epmapp_dbDataSet)
Try
MessageBox.Show("Su perfil ha actualizado exitosamete")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Clear_Form_tap1()
disabling_controlstap1()
btn_saveprofile_oninside_profileedit_tap1.Visible = False
btn_cancelprofileedit_onprofileselectiontap1.Visible = False
btn_deleteprofile_oninsideprofiledittap1.Visible = False
btn_editprofile_oncboxselectiontap1.Visible = False
btn_newprofile_onload_tap1.Visible = True
cbox_profiles.Enabled = True
ErrorProvider1.Clear()
End Sub
I have try a few codes but none works for me. Can any one help me with a code for this small issue?

If I followed this correctly, when you delete a record you are doing so directly in the database. However, you are not updating your datasource (GeneralInfoBindingDource). My guess is you have the same issue when you create a new item. The database is updated, so when it reloads the data from the database its correct. (When you reopen it).
You need to update your datasource.
Your save works because you are updating the datasource, rather than writing changes to the database without updating it.
Me.GeneralInfoBindingSource.EndEdit()
Me.GeneralInfoTableAdapter.Update(Me.Epmapp_dbDataSet)

Related

Update From DataGridView to Database

Dim sb As New MySqlConnectionStringBuilder
sb.Server = Form1.hostname.Text
sb.UserID = Form1.rootuser.Text
sb.Password = Form1.rootpassword.Text
sb.Database = Form1.hostdb.Text
sb.Port = Form1.hostport.Text
Using connection As New MySqlConnection(sb.ConnectionString)
Try
connection.Open()
Dim adapter1 As New MySqlDataAdapter(TextBox1.Text, connection)
Dim cmdb1 = New MySqlCommandBuilder(adapter1)
Dim ds As New DataSet
Dim words As String() = TextBox1.Text.Split(New Char() {" "c})
Dim tablenamewords = (words(3))
adapter1.Update(ds, tablenamewords)
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Using
It's giving me this error:
Update unable to find TableMapping['creature_template'] or DataTable 'creature_template'.
I want to select items then use a DataGrid to update them.
Note: tablenamewords = "creature_template"
You can solve this in alot of different methods.
I prefer to update the DB with a single query every time the the user ends editing a cell.
BUT FIRST you have to bind a source to your DataGridView!
How to bind a source:
Go to your application design an click on your DataGridView
Click on the pause/start like little button as shown:
Click on the "ComboBox" like textbox labeled as "chose data source" as shown and click on it:
It will open a "form", click on the Add data source as shown:
Follow the wizard, you can do it without any furhter explanation!
Well done, you almost completed it. Just go in your code, and look for this sub:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.your_table_nameTableAdapter.Fill(Me.your_db_nameDataSet.your_table_name)
End Sub
The line inside your Form1_Load Sub will upload the data inside your DataGridView, leave it there if you want it to load with the form or cut/paste it wherever you like.
Now you can add this the code to programmatically update the DB:
Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Try
Dim location As Point = DataGridView1.CurrentCellAddress
Dim sqlCmd As String = "UPDATE table_name SET " & _
DataGridView1.Columns(location.X).Name.Replace("DataGridViewTextBoxColumn", "") & " = #Data " & _
"WHERE " & _
DataGridView1.Columns(0).Name.Replace("DataGridViewTextBoxColumn", "") & " = #ID"
Using myConn As New SqlConnection(My.Settings.VISURE_DA_PDFConnectionString)
myConn.Open()
Using myCmd As New SqlCommand(sqlCmd, myConn)
myCmd.Parameters.Add("#Data", SqlDbType.VarChar)
myCmd.Parameters.Add("#ID", SqlDbType.Int)
myCmd.Parameters("#Data").Value = DataGridView1.Rows(location.Y).Cells(location.X).Value
myCmd.Parameters("#ID").Value = DataGridView1.Rows(0).Cells(location.X).Value
myCmd.ExecuteNonQuery()
End Using
myConn.Close()
End Using
Catch ex As Exception
Err.Clear()
End Try
End Sub
Remarks:
location.X is the col index, location.Y is the row index
DataGridView1.Columns(0).Name This is my ID (primary key) and it is always in the first column. Change it with yours.
Don't forget to add .Replace("DataGridViewTextBoxColumn", "") whan you are getting your column name
As previously said, this code will update your DB every time the user edits one cell on your DataGridView updating only the edited cell. This is not a big issue because if you want to edit two ore more cell, every time you leave an edited cell the method DataGridView1_CellEndEdit is fired!

UltraWinGrid Auto Refresh

In my vb.net project, I have 3 forms. home_mdi, Viewfrm and AddDatafrm.
Viewfrm has an UltraWinGrid on it, which is displaying some data. When I click the add data button, AddDatafrm opens. When data is saved, the form then closes.
At this point, I want the UltraWinGrid on Viewfrm to update/refresh and display the data that I added. At the moment, it doesn't display it until I close Viewfrm and then open it again.
The images show this. (Data is not there at the start, it then gets added and does not appear. The final image is the form displaying the new data, after I've re-opened it.
How do I change this?
Current code:
To open the Add form
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Using fp = New frmAddData(Globals.m_database)
If fp.ShowDialog() = DialogResult.OK Then
ugData.DataSource = Nothing
getPeople()
End If
End Using
End Sub
To save the entered information (on the Add form)
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim m_cn As New OleDbConnection
m_cn = Globals.m_database.getConnection()
If txtFirstName.Text = "" Then
MsgBox("First name cannot be blank")
ElseIf txtLastName.Text = "" Then
MsgBox("Last name cannot be blank")
ElseIf txtAge.Text = "" Then
MsgBox("Age cannot be blank")
ElseIf txtPostCode.Text = "" Then
MsgBox("Postcode cannot be blank")
Else
Dim personID As Integer = database.SaveNewPerson(txtFirstName.Text, txtLastName.Text, txtAge.Text, txtPostCode.Text, m_cn)
MsgBox("Save successful")
txtFirstName.Text = ""
txtLastName.Text = ""
txtAge.Text = ""
txtPostCode.Text = ""
Globals.savedValue = True
Me.Close()
End If
End Sub
Call to load the database on the View form:
Public Sub getPeople()
Try
Dim sql As String = "SELECT * FROM tblPerson ORDER BY [personID] ASC;"
Dim cm As New OleDbCommand(sql, Globals.m_database.getConnection())
Dim da As New OleDbDataAdapter(cm)
Dim dt As New DataTable()
da.Fill(dt)
ugData.DataSource = dt
Catch Ex As Exception
mdi1.errorLog(Ex.Message, Ex.StackTrace)
MsgBox("Failed to retrieve data, refer to error log")
End Try
End Sub
In a WinForm app, a modal dialog is closed automatically by the engine if a button is pressed and its DialogResult property is set to anything but None. Then the Winform engine sets the form DialogResult to the same property of the button, exits from the ShowDialog call and returns the DialogResult property of the button clicked.
Usually this is more than enough to handle situations like yours above. (Or, in general situations where a user choose between Yes/No or OK/Cancel scenarios)
In your code (as explained in chat) you have the DialogResult property of the Save button set to DialogResult.None. This, means that the Winforms engine doesn't close automatically your form and you need to write your own closing routine.
But, if you forget to set the Form property DialogResult to DialogResult.OK, your calling code will never be able to refresh the grid because the test for DialogResult.OK fails.
So, whatever closing code you have to close the fromAddData instance, remember to set the form DialogResult property with
Me.DialogResult = DialogResult.OK
or, if something is gone wrong, with
Me.DialogResult = DialogResult.Cancel

Set radio button list from vb code behind

I have a radio button list. When the page is loaded I have some scripts and other things that run to determine if an ID has passed or failed a test. So what I am trying to actually do is when that page loads set my radio button to fail after the script runs
Here is the list:
<asp:radiobuttonlist id="rblInspectionStatus" CssClass="descbold" runat="server" repeatColumns="2" repeatDirection="Horizontal">
<asp:listitem Value="Pass">Pass</asp:listitem>
<asp:listitem Value="Fail">Fail</asp:listitem>
</asp:radiobuttonlist>
What I have tried is:
rblInspectionStatus.Items.FindByValue("Fail").Selected = True
rblInspectionStatus.Items.FindByText("Fail").Selected = True
rblInspectionStatus.SelectedIndex |SelectedItem | SelectedValue
I don't know what you are trying to do in that Sub or as User Tony Hinkle and User NoAlias are trying to say is correct but this is my assumption:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
cn.Open() 'Opens the connection
cmd = New SqlCommand("SELECT PF FROM TABLE WHERE ID = '" & Session("ID") & "'", cn)
drr = cmd.ExecuteReader
If drr.Read Then
rblInspectionStatus.ClearSelection()
rblInspectionStatus.Items.FindByValue(drr.Items("PF")).Selected = True
'FIELD PF data either Pass or Fail
ElseIf Not drr.Read Then
rblInspectionStatus.ClearSelection()
rblInspectionStatus.SelectedIndex = -1
End If
cn.Close() 'Close the connection
End Sub

vb.NET: Textbox TextChange

Good day:)
I have a program with textboxes for Reference Number, Payee, Office and Address... What I want is that if the Reference Number exists in Obligation Table it will automatically put Payee, Office and Address, If not, you will type Payee's name but if exists in Payees table automatically it will put the Office and Address...
my problem is that it displays the correct result BUT a message box saying "No current query in data reader." I think the code are overlapping each other but i don't know how to resolve this.
Here's my code for txtRefNo.Text:
Private Sub txtRefNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRefNo.TextChanged
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT DISTINCT ref_no, payee from bims_obligations " & _
"WHERE ref_no = '" & txtRefNo.Text & "'")
If Reader.HasRows Then
While Reader.Read
txtPayee.Text = Reader("payee").ToString()
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
txtPayee.Enabled = False
txtOffice.Enabled = False
txtAddress.Enabled = False
certALoadGrid()
End While
Else
txtPayee.Clear()
txtOffice.Clear()
txtAddress.Clear()
txtPayee.Enabled = True
txtOffice.Enabled = True
txtAddress.Enabled = True
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
and for txtPayee.text:
Private Sub txtPayee_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPayee.TextChanged
Try
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
Reader = modGlobalFunctions.executeQuery("SELECT * from bims_payee " & _
"WHERE payee = '" & txtPayee.Text & "'")
If Reader.HasRows Then
While Reader.Read
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
End While
Else
txtOffice.Clear()
txtAddress.Clear()
End If
Reader.Close()
modGlobalFunctions.Connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "BIMS", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
modGlobalFunctions.Connection.Close()
End Sub
Looking forward for answers... or is there an if statement that if refNo exists then it will disregard textChange of txtPayee??? God bless :)
I believe that this line:
txtPayee.Text = Reader("payee").ToString()
Will cause txtPayee_TextChanged to fire. Which then calls:
modGlobalFunctions.Connection.Close()
modGlobalFunctions.connectDatabase()
You haven't shown us the code for those functions, but the names are certainly suggestive. You then use this global connection object inside txtPayee_TextChanged, and close it again at the bottom.
Finally, the code inside txtRefNo_TextChanged resumes with these lines:
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
But that Reader is associated with a connection that's been closed twice (or replaced, in some fashion, again, you've not shown that code) - and you'll have an error.
This is but one reason why having a globally shared Connection object is a bad idea (it's also bad if/when you want to start using background workers, Tasks, or anything else that involves multithreading).
It would be far better to just have a connection string in your modGlobalFunctions module. Then, inside each function, create separate SqlConnection and SqlCommand objects - placing each within Using statements. That way they will not interfere with each other.
I'm guessing that the
modGlobalFunctions.Connection.Close()
Were added at the top of each function to cure an earlier symptom of the same issue
Also, as indicated in my comment - don't catch Ex as Exception and just display Ex.Message. You have no idea what exceptions might be thrown, and you're disposing of a lot of useful information (such as the Stack Trace and Inner Exception)
E.g. this is how I'd write your first sub:
Private Sub txtRefNo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRefNo.TextChanged
Using conn As New SqlConnection(ConnectionString) 'Our own private connection, no one else can interfere
Using cmd As New SqlCommand("SELECT DISTINCT ref_no, payee from bims_obligations WHERE ref_no = #RefNo", conn) 'Using parameters, safer SQL
cmd.Parameters.AddWithValue("#RefNo", txtRefNo.Text)
conn.Open() 'Open the connection
Dim Reader = cmd.ExecuteReader()
If Reader.HasRows Then
While Reader.Read
txtPayee.Text = Reader("payee").ToString()
txtOffice.Text = Reader("office").ToString()
txtAddress.Text = Reader("address").ToString()
txtPayee.Enabled = False
txtOffice.Enabled = False
txtAddress.Enabled = False
certALoadGrid()
End While
Else
txtPayee.Clear()
txtOffice.Clear()
txtAddress.Clear()
txtPayee.Enabled = True
txtOffice.Enabled = True
txtAddress.Enabled = True
End If
Reader.Close() 'Not really necessary, but anyway
End Using
End Using 'These have cleaned up our connection and command objects
'If an exception has occurred, we don't know what it is, or how to recover
'So we don't try and catch it.
End Sub

how to change selected option of textbox based on datareader result vb

.hi everyone I have this code:
Private Sub EditPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'InventorySysDataSet.tb_master_products' table. You can move, or remove it, as needed.
Me.Tb_master_productsTableAdapter.Fill(Me.InventorySysDataSet.tb_master_products)
sqlCnn = New SqlConnection("Data Source=ZEREY\SQLEXPRESS2008;Initial Catalog=InventorySys;Integrated Security=SSPI")
Me.txtRowId.Text = Form1.txtRowId.Text
'MsgBox(Me.txtRowId.Text)
sql = "Select * from tb_master_inventory_per_day where Inventory_Date = " & txtRowId.Text & ""
Dim upcmd As New SqlCommand("Select * from tb_master_inventory_per_day where Row_Id = #Row_Id", sqlCnn)
upcmd.Parameters.Add(New SqlParameter("#Row_Id", Me.txtRowId.Text))
upcmd.Connection.Open()
Try
Dim dr As SqlDataReader = upcmd.ExecuteReader()
If dr.Read Then
txtInventoryDate.Text = dr.Item("Inventory_Date")
cboProductCode.DisplayMember = dr.Item("Product_Code")
txtQty.Text = dr.Item("Product_Count")
Else
MessageBox.Show("Error!")
End If
Catch ex As SqlException
If ex.Number <> 0 Then
'ErrorProvider1.SetError(Me.txtuseridprofile, "Login Id: " &
'Me.txtuseridprofile.Text & " :Not Found!")
upcmd.Connection.Close()
Exit Sub
End If
End Try
upcmd.Connection.Close()
End Sub
what i want to do is to automatically change the selected option of the cboProductCode on page load depending on the result of a query executed onload also.
help pls! TIA!
.Haha! it's funny that i have tried so many ways but not tried using cboProductCode.Text instead of cboProductCode.DisplayMember. It now works! :D