Reputation: 499
I building a small app writen in Visual Basic.NET, but i need your help. I have DataGridView to display my database and i want make "update" button to update from DataGridView to database. But before update, i want to selected row in DataGridView like this:
and show to textbox. So, i made a change from textbox for update my database. How to do it?
Here is my code for update:
Private Sub btnPesEdit_Click(sender As Object, e As EventArgs) Handles btnPesEdit.Click
Koneksi()
Dim konfEdit As DialogResult = MsgBox("Apakah data yang di-update sudah benar?",
MessageBoxButtons.YesNo, "Konfirmasi")
Try
str = "UPDATE data_pesanan SET (@namakons, @almtkons, @tglpesan, @jenispaket, @jmlpesan, @totaluang) WHERE (@kodekons)"
comm = New MySqlCommand(str, conn)
comm.Parameters.AddWithValue("@kodeKons", txtPesKodeKonsu.Text)
comm.Parameters.AddWithValue("@namakons", txtPesNamaKonsu.Text)
comm.Parameters.AddWithValue("@almtkons", txtPesAlmtKonsu.Text)
dtPesTglPesan.CustomFormat = "dd-MM-yyyy"
comm.Parameters.AddWithValue("@tglpesan", dtPesTglPesan.Value)
comm.Parameters.AddWithValue("@jenispaket", lblPesJenisPkt.Text)
comm.Parameters.AddWithValue("@jmlpesan", Convert.ToInt32(txtPesJmlPesan.Text))
comm.Parameters.AddWithValue("@totaluang", Convert.ToInt32(lblPesTotal.Text))
comm.ExecuteNonQuery()
conn.Close()
Catch ex As Exception
MsgBox(ex.InnerException.Message)
'MsgBox(ex.Message)
End Try
End Sub
And here is my code to display from database into DataGridView:
Private Sub tablePesanan()
Koneksi()
comm = New MySqlCommand("select * from data_pesanan", conn)
dataAdap = New MySqlDataAdapter(comm)
Dim dataTbl As New DataTable
dataAdap.Fill(dataTbl)
tblPesList.DataSource = dataTbl
tblPesList.ReadOnly = True
End Sub
Note: I'm sorry if my English is bad. I hope you understand what I'm saying.
Upvotes: 0
Views: 1515
Reputation: 54417
As suggested in the comments, you should use data-binding. You should bind your DataTable
to a BindingSource
and then bind that to the grid and the other controls, e.g.
myBindingSource.DataSource = myDataTable
myDataGridView.DataSource = myBindingSource
myTextBox.DataBindings.Add("Text", myBindingSource, "ColumnName")
You can bind as many individual controls to as many columns as you like that way. Just be sure to bind the appropriate control property. It is Text
for a TextBox
but SelectedValue
for a ComboBox
, Value
for a DateTimePicker
, etc. Also be aware that a DateTimePicker
doesn't really support binding nullable data so, if your data might contain nulls in the date column, you will need some manual intervention.
When it's time to save data, you need to make sure that any pending edit is committed before actually saving, e.g.
Validate()
myBindingSource.EndEdit()
myDataAdapter.Update(myDataTable)
Upvotes: 1