How to edit the selected row when a button is clicked? - vb.net

I was trying to edit the data from the selected rows in datagridview if the button is clicked and put it in the textbox to update the data and what's happening is if I select a row it is directly putted in the textboxes before I click the edit button, but what I want is if I select a row then click the edit button and the data from the selected rows will be putted in the textboxes provided. Can someone help me please..
here is my code in datagridview:
index = e.RowIndex
Dim selectedRow As DataGridViewRow
selectedRow = DataGridView1.Rows(index)
TextBox8.Text = selectedRow.Cells(1).Value.ToString
TextBox1.Text = selectedRow.Cells(2).Value.ToString
TextBox2.Text = selectedRow.Cells(3).Value.ToString
TextBox3.Text = selectedRow.Cells(4).Value.ToString
TextBox4.Text = selectedRow.Cells(5).Value.ToString
TextBox5.Text = selectedRow.Cells(6).Value.ToString
TextBox6.Text = selectedRow.Cells(7).Value.ToString
ComboBox1.Text = selectedRow.Cells(8).Value.ToString
TextBox9.Text = selectedRow.Cells(9).Value.ToString
then this is my code in edit button
Try
Dim cmd As New MySqlCommand
connect.Open()
cmd.Connection = connect
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
cmd.CommandText = "update tbl_book_info set (Title = '" & TextBox1.Text & "',Author = '" & TextBox2.Text & "',Copyright = '" & TextBox3.Text & "',Publisher = '" & TextBox4.Text & "',Place = '" & TextBox5.Text & "',Copies = '" & TextBox6.Text & "', Subject = '" & ComboBox1.Text & "', ClassNo = '" & TextBox8.Text & "',Registered by = '" & TextBox9.Text & "',Time = '" & TextBox10.Text & "',Date = '" & TextBox11.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Already Updated!")
MessageBox.Show("update tbl_book_info set (Title = '" & TextBox1.Text & "',Author = '" & TextBox2.Text & "',Copyright = '" & TextBox3.Text & "',Publisher = '" & TextBox4.Text & "',Place = '" & TextBox5.Text & "',Copies = '" & TextBox6.Text & "', Subject = '" & ComboBox1.Text & "', ClassNo = '" & TextBox8.Text & "',Registered by = '" & TextBox9.Text & "',Time = '" & TextBox10.Text & "',Date = '" & TextBox11.Text & "')")
data = New DataTable()
DataGridView1.DataSource = data
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
da.Fill(data)
Catch ex As Exception
End Try

Dim x As Integer
Dim y As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = DataGridView1.SelectedCells(0).Value()
x = DataGridView1.SelectedCells(0).RowIndex
y = DataGridView1.CurrentCell.ColumnIndex
DataGridView1.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
DataGridView1.Enabled = True
DataGridView1.Rows(x).Cells(y).Value = TextBox1.Text
End Sub

Related

{change the color of DataGrid Cell after updating rows}

basically what i want is when change the status and update it will change the color of that updated cell
here is my code:
Private Sub Btnupdate_Click(sender As Object, e As EventArgs) Handles btnupdate.Click
Try
Dim datePublish As String = Format(dtpDatePublish.Value, "yyyy-MM-dd")
If txtAccessionNo.Text = "" Or txtAuthor.Text = "" Or txtTitle.Text = "" Or TxtBoxISBN.Text = "" Or txtPublisher.Text = "" Or CBSection.Text = "" Or TxtBoxSubject.Text = "" Or TxtBoxYearPub.Text = "" Or TxtBoxShelf.Text = "" Or TxtBoxCallNumber.Text = "" Then
MsgBox("All fields are required to be filled up.", MsgBoxStyle.Exclamation)
Else
sql = "SELECT * FROM `books` WHERE `AccessionNo` = '" & txtAccessionNo.Text & "'"
reloadtxt(sql)
If dt.Rows.Count > 0 Then
panelstatus.Visible = True
sqledit = "UPDATE `books` SET `Isbn`='" & TxtBoxISBN.Text & "',
`BookSection` = '" & CBSection.SelectedItem & "', `Subject` = '" & TxtBoxSubject.Text & "', `Title` = '" & txtTitle.Text & "',
`Author` = '" & txtAuthor.Text & "', `JointAuthor` = '" & txtjointauthor.Text & "', `Publisher` = '" & txtPublisher.Text & "',
`YearPublish` = '" & TxtBoxYearPub.Text & "', `Edition` = '" & TxtBoxEdition.Text & "', `Volume` = '" & TxtBoxVolume.Text & "',
`Aquistion` = '" & CBAquisition.SelectedItem & "', `DateAquired` = '" & datePublish & "', `SponsorPrice` = '" & TxtBoxPrice.Text & "',
`Shelf` = '" & TxtBoxShelf.Text & "', `CallNumber` = '" & TxtBoxCallNumber.Text & "', `Remarks` = '" & TxtBoxRemarks.Text & "', `Status` = '" & CBstatus.SelectedItem & "' WHERE `AccessionNo` = '" & txtAccessionNo.Text & "'"
save_or_update(sql, sqladd, sqledit, "Books has been updated in the database.", "New books has been saved in the database.")
Call InventoryAdd_Load(sender, e)
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
here is my cell formatting code
Private Sub DtgList1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dtgList1.CellFormatting
For Each row As DataGridViewRow In dtgList1.Rows
If row.Cells(17).Value = "Available" Then
row.DefaultCellStyle.ForeColor = Color.White
row.DefaultCellStyle.ForeColor = Color.Red
End If
Next
End Sub
When adding row colours to DataGridViews, I normally handle the Paint event. The error 'Conversion from string "Available" to type 'Double' is not valid suggests that row.Cells(17).Value is a Double, not a string. Are you sure that's the correct column?
From your code, I'm guessing your column is called 'Status'. If not, rename below as needed, or continue to use column number but ensure it's the correct column. As you are using Select * to populate your table, I'd suggest using a Column Name is more reliable as column order may change or new columns added to the database in future.
Private Sub dtgList1_Paint(sender As Object, e As PaintEventArgs) Handles dtgList1.Paint
For Each rw As DataGridViewRow In dtgList1.Rows
If rw.Cells("Status").Value = "Available" Then
rw.DefaultCellStyle.ForeColor = Color.White
Else
rw.DefaultCellStyle.ForeColor = Color.Red
End If
Next
End Sub

trying to update a passowrd and username in database i get operator error

Imports System.Data.OleDb
Imports System.Data
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ran As New Random
TextBox2.Text = ran.Next(1, 8)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Or MaskedTextBox3.Text = "" Then
MsgBox("Please fill all text boxes With the required info")
Else
Dim cmd As OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\users\nikh8610\Documents\users.accdb")
Dim str As String
con.Open()
str = "UPDATE users SET username = '" & TextBox1.Text & "'WHERE (ID = '" & TextBox2.Text & "') AND password='" & MaskedTextBox3.Text & "' WHERE (ID = '" & TextBox2.Text & "')"
cmd = New OleDbCommand(str, con)
cmd.ExecuteNonQuery()
con.Close()
End If
End Sub
End Class
Your query isn't valid. You are using two WHERE parts on the query. Try the following:
str = "UPDATE users SET username = '" & TextBox1.Text & "' WHERE ID = '" & TextBox2.Text & "' AND password='" & MaskedTextBox3.Text & "'"
You also don't UPDATE the password of the user. You can use something like the following to UPDATE the username and password.
str = "UPDATE users SET username = '" & txtUsername.Text & "', password = '" & txtNewPassword.Text & "' WHERE ID = '" & txtUserID.Text & "' AND password = '" & txtOldPassword.Text & "'"
You should also use prepared statements to UPDATE the user information:
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.CommandText = "UPDATE users SET username = ?, password = ? WHERE ID = ? AND password = ?"
cmd.Parameters.Add("NewUsername", OleDbType.VarWChar, 50)
cmd.Parameters.Add("NewPassword", OleDbType.VarWChar, 50)
cmd.Parameters.Add("UserID", OleDbType.Long)
cmd.Parameters.Add("OldPassword", OleDbType.VarWChar, 50)
cmd.Parameters(0).Value = txtNewUsername.Text
cmd.Parameters(1).Value = txtNewPassword.Text
cmd.Parameters(2).Value = txtUserID.Text
cmd.Parameters(3).Value = txtOldPassword.Text
cmd.Prepare()
cmd.ExecuteNonQuery()

Register VB.Net Using Access Database

i have a problem regarding register form which i try to make it send to database ( add new record ) using data provided but its not working. Thank you very much
Here is the UI :
Heres my code :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim nama, uname, password, email, jk As String
Dim idusr As Integer
nama = TextBox1.Text
uname = TextBox2.Text
password = TextBox3.Text
email = TextBox5.Text
jk = ComboBox1.SelectedValue
Randomize()
' The program will generate a number from 0 to 50
idusr = Int(Rnd() * 50) + 1
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Then
MsgBox("Please Fill All The Box First !!!")
ElseIf TextBox3.Text <> TextBox4.Text Or TextBox3.TextLength <= 8 Then
MsgBox("Password do not match or missing !!!")
Else
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Michael\Tugas Materi Kuliah\VB\TA\DBUtama.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim str = "Insert into [User]([IDUSR],[Nama],[Uname],[Pass],[Jenis Kelamin],[Email]) Values ('" & idusr & "','" & nama & "','" & uname & "','" & password & "','" & jk & "','" & email & "') ;"
Dim cmd As OleDbCommand = New OleDbCommand(str, conn)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
MsgBox("Something broke, i know its you !!")
End Try
End If
End Sub
and Database :
idusr is numeric, thus no quotes:
Dim str = "Insert into [User]([IDUSR],[Nama],[Uname],[Pass],[Jenis Kelamin],[Email]) Values (" & idusr & ",'" & nama & "','" & uname & "','" & password & "','" & jk & "','" & email & "') ;"
And do leave out all those exclamation marks. Users are not idiots.
Also, get someone to proofread the prompts and captions.

How to update the selected rows in datagridview?

i was trying to update the data from the selected row on datagridview but when i clicked the Update button all the data even the not selected rows are edited..
here is my code:
connect.Open()
DataGridView1.SelectedRows(0).Cells(1).Value = TextBox8.Text
DataGridView1.SelectedRows(0).Cells(2).Value = TextBox1.Text
DataGridView1.SelectedRows(0).Cells(3).Value = TextBox2.Text
DataGridView1.SelectedRows(0).Cells(4).Value = TextBox3.Text
DataGridView1.SelectedRows(0).Cells(5).Value = TextBox4.Text
DataGridView1.SelectedRows(0).Cells(6).Value = TextBox5.Text
DataGridView1.SelectedRows(0).Cells(7).Value = TextBox6.Text
DataGridView1.SelectedRows(0).Cells(8).Value = ComboBox1.Text
DataGridView1.SelectedRows(0).Cells(9).Value = TextBox9.Text
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
cmd.CommandText = "update tbl_book_info set Title = '" & TextBox1.Text & "',Author = '" & TextBox2.Text & "',Copyright = '" & TextBox3.Text & "',Publisher = '" & TextBox4.Text & "',Place = '" & TextBox5.Text & "',Copies = '" & TextBox6.Text & "',Subject = '" & ComboBox1.Text & "',ClassNo = '" & TextBox8.Text & "',Registered = '" & TextBox9.Text & "',Time = '" & TextBox10.Text & "',Date = '" & TextBox11.Text & "' where ISBN = ISBN "
cmd.ExecuteNonQuery()
MsgBox("Data Saved!")
EDIT.Text = "Edit"
data = New DataTable()
DataGridView1.DataSource = data
da = New MySqlDataAdapter("Select * from tbl_book_info", connect)
da.Fill(data)
please help.. I'm a beginner in vb.net

Save all rows in Datagridview when Checkbox column is true

Good Morning
I have a program that looks like this.
Form Design
I have a button named Multiple Select and when I click that the button will call SaveCheckedRecords() and here is the code for it
Public Sub SaveCheckedRecords()
Dim failed = False
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells(0).Value = True Then
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Label2.Text = DataGridView1.Item("ItemCode", i).Value
Label3.Text = DataGridView1.Item("Description", i).Value
Label4.Text = DataGridView1.Item("ReflectedQty", i).Value
Label5.Text = DataGridView1.Item("UOM", i).Value
Label6.Text = DataGridView1.Item("UnitPrice", i).Value
Label7.Text = DataGridView1.Item("Total", i).Value
Label8.Text = DataGridView1.Item("Remarks", i).Value
standard() '<------------- Call this Sub
insert() '<------------- Call this Sub
failed = True
Exit For
End If
Next
If Not failed Then
MsgBox("Please select an item to receive")
End If
End Sub
Now my goal based on the code above is to transfer the data from datagridview rows to labels and call some Subs
Here is the code for the standard and insert
Private Sub standard()
Dim con As MySqlConnection = New MySqlConnection("server=localhost;userid=root;password=admin1950;database=inventory")
Dim cmd As MySqlCommand = New MySqlCommand("select StandardUOM,QtyPerUoM from item_master_list where ItemCode = '" & Label2.Text & "'", con)
Dim reader As MySqlDataReader
con.Open()
reader = cmd.ExecuteReader
While reader.Read
Label9.Text = reader.GetString("StandardUOM")
Label10.Text = reader.GetString("QtyPerUoM")
End While
End Sub
Private Sub insert()
DataGridView1.Columns.RemoveAt(0)
Dim con1 As MySqlConnection = New MySqlConnection("datasource=localhost;database=inventory;userid=root;password=admin1950")
Dim cmdinsert As MySqlCommand = New MySqlCommand("insert into receiving (RINo,PONo,ItemCode,Description,QtyPack,PackUoM,UnitPrice,Total,Remarks,ExpiryDate,QtyStan,StanUoM,PCS) values ('" & frm_Add_Receiving_Items.TextBox1.Text & "','" & Label1.Text & "','" & Label2.Text & "','" & Label3.Text & "','" & Label11.Text & "','" & Label5.Text & "','" & Label6.Text & "','" & Label7.Text & "','" & Label8.Text & "','" & DateTime.Now.ToString("yyyy-MM-dd") & "','" & Label12.Text & "','" & Label9.Text & "','" & Label10.Text & "')", con1)
con1.Open()
cmdinsert.ExecuteNonQuery()
con1.Close()
frm_Add_Receiving_Items.generate_rec_form()
updateRI()
loadlist1()
frm_Add_Receiving_Items.Button6.Enabled = False
Label2.Text = "Label2"
End Sub
All I want to do is to save the value of datagridview when checkboxcolumn(0) is True whats wrong with my code?
TYSM