Delete a row through DataGridView - vb.net

I have a Button that lists to me everything from a database and another Button that was made to delete something from database by "Name". To do that, I have a TextBox where I input the "Name" and delete it from the database.
To make things easy and faster I had another solution which is simpler than what I am currently doing. What I want it to do is click on a row and then press the delete Button and have the row be deleted from the database. I found this solution but this doesn't work:
For Each row As DataGridViewRow In myDataGrid.SelectedRows
myDataGrid.Rows.Remove(row)
Next
Basically what I have to do in the code is make a query and select the row that I want right?

My apologies I am not able to comment. In either case, if you are trying to delete the record from the database, you will have to use a delete query.
Below is an example on how to do it:
delete selected row from datagridview and datasource table
Without using a stored procedure you can use this code:
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim cnstring As String = "Your connection String"
Dim sqlstring As String = "Delete from yourTable where column= your record"
cn = New OleDbConnection(cnstring)
cmd = New OleDbCommand(sqlstring, cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()

The For[...]Next statement will only delete the DataGridViewRow from the DataGridView. It won't commit any changes to the database.
A DataGridView is a view of the data. You would need to commit the changes on the DataSet.
If you want a more specific answer post the code that shows how you are binding the data to the DataGridView.

Related

How can i set the value from the last row in an specific column in a variable in VB.Net

I'm develop an application using forms in vb.net with visual studio 2019
I have code in the event click for one button
Dim oda As New OleDbDataAdapter
Dim ods As New DataSet
Dim consulta As String
Dim cadena As New OleDbConnection
Dim comando As New OleDbCommand
Try
cadena.Open()
comando = New OleDbCommand("Insert into QRQC (Nombre,NumControl,Fecha,Hora,Turno)" &
"values(txt_nombre,txt_numControl,lbl_fecha,lbl_hora,cBox_turno)", cadena)
consulta = "Select *From QRQC"
oda = New OleDbDataAdapter(consulta, cadena)
ods.Tables.Add("QRQC")
oda.Fill(ods.Tables("QRQC"))
Dim row As Integer
row = ods.Tables("QRQC").Rows.Count - 1
courrentId = ods.Tables("QRQC")(row)("ID_QRQC").ToString()
frm_newPt2.lbl_folioQRQC.Text = courrentId
cadena.Close()
Catch ex As Exception
MsgBox("Error al generar el registro en la base de datos", vbCritical, "Aviso")
Console.WriteLine(ex)
cadena.Close()
GoTo skip
End Try
Everything goes perfectly, but when I delete some record on my DB this part of the code always return the value 102
courrentId = ods.Tables("QRQC")(row)("ID_QRQC").ToString()
How can i solve this problem?
First of all, your insert command is wrong, and will not work.
You have "values(txt_nombre. etc etc."
But that is just a string and NOT the actual values from the form. So you are actually going to "instert txt_nombre" into that table and NOT the value of that label or text box on the form!!!
So you need to fix and get your insert command working FIRST.
And if this is just editing data then consider using the data binder, since navigation, editing, deleting and saving of data to/from the table can occur 100% automatic whiteout ANY code on your part.
so first up is to fix that insert command. You can't JUST use a string with the names of the controls else that would actually as noted try to insert the names of the controls as text and NOT the values of the controls.
And lets clean up a few other things. No need for a dataset, since a dataset is a SET of tables - we only dealing with one table (so use a data table).
But as noted, before we mess with data tables, we have to fix that insert command.
It will, can look like this:
Dim strSQL As String
strSQL = "Insert into QRQC (Nombre,NumControl,Fecha,Hora,Turno) " &
"VALUES(#nombre,#numControl,#fecha,#hora,#turno)"
Using cmdSQL As New OleDbCommand(strSQL,
New OleDbConnection(My.Settings.TestDB))
cmdSQL.Parameters.Add("#nombre", OleDbType.Integer).Value = txt_nombre.Text
cmdSQL.Parameters.Add("#numControl", OleDbType.Integer).Value = txt_numControl.Text
cmdSQL.Parameters.Add("#fecha", OleDbType.Integer).Value = lbl_fecha.Text
cmdSQL.Parameters.Add("#hora", OleDbType.Integer).Value = lbl_hora.Text
cmdSQL.Parameters.Add("#turno", OleDbType.Integer).Value = txt_nombre.Text
cmdSQL.Connection.Open()
cmdSQL.ExecuteNonQuery()
End Using
So you have to "replace" the string values in the sql with the ACTUAL values you are using.
You also don't show where/how you setup your connection to the database. I guessed that you used the applications settings and the connection builder - so you have to change TestDB to your actual connection that you used.
The above will thus get your insert command working.
At that point, you can post a new question in that after you do a insert, how to get the new autonumber primary key, or whatever else you wanted to do, but your insert statement as written will not work.
As noted, perhaps it better to use data bound controls. This will result in a Access like design experience, and you not having to write ANY code to edit a table in vb.net.
And it not clear if the control names I used are correct (or they are even controls on the form), but if they are, then ".Text" is required to grab the values. You have to of course change (check) that the control names I used and guessed are correct.
You also have to change the data type "integer" I used in above to the correct data types. For text I recommend you use .VarWChar

Deleting SQL datarow from a table swipes position of first and second row in vb.net

adding updating everything is fine even delete command is working but the strange part is after executing del command from vb.net application it swipes the position of EMPLOYEE_IDAND NAMEit shows normally in datagridviewafter adding or updating but specifically after deleting the record position of these to column changes until I stop the application and re run the entire project for debugging
Dim con As New MySqlConnection("server=localhost; user=root; password=Masoom1; database=airtech_db; convert zero datetime=true;")
Dim cmd As New MySqlCommand
Dim dt As New DataTable
Dim da As New MySqlDataAdapter
Dim sql As String
Dim DR As MySqlDataReader
Dim SQL_CMD_TXT As String
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
With OBJECT_DATAGRIDVIEW
.Size = New Size(587, 242)
.Location = New Size(221, 171)
End With
Try
'DB CMD EXECUTION
con.Open()
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
da.SelectCommand = cmd
da.Fill(dt)
'Command for datagridview object
With OBJECT_DATAGRIDVIEW
.DataSource = dt
'Scroll to the last row.
.Name = "MYDATAGRIDVIEW"
.FirstDisplayedScrollingRowIndex = .RowCount - 1
End With
con.Close()
Catch ex As Exception
Dim MEB = MessageBox.Show("ERROR FOR SQL CMD EXECUTION SECTION-" & ex.Message,
"SQL CMD EXECUTION", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
attaching the normal and after delete result in images
enter image description here
I am not sure I completely understood your problem, but your problem could that the datagridview generates the columns automatically. See: DataGridView.AutoGenerateColumns
Instead of doing SELECT * FROM is would better to select just the fields you need. If you add more fields to your table in the future, the columns in the datagridview may be displaced because they are in no particular order.
Rather than add the datagridview to your form at runtime:
EMPLOYEE_DEL_FRM.Controls.Add(OBJECT_DATAGRIDVIEW)
I would add it directly in the form layout (so you can see it at design time), and then customize it, bind each column to a database field. The appearance of the grid will be more predictable. Here is a small guide: How to bind datatable/list to datagridview with headers?
Relying on AutoGenerateColumns is not a great idea, because this will show all columns (usually not desirable) and not necessarily in the order that you want.
Other remarks:
Records can be edited or deleted directly in the datagridview, by simply selecting one or more rows, and pressing the Del key. Then just invoke the DataAdapter to commit the changes to the database. You should not even be doing DELETE FROM. Just let the user use the datagridview. The benefit is that if the user makes a mistake, you can roll back changes because you are using a datatable. Here you are deleting immediately and without warning.
Don't do stuff like:
SQL_CMD_TXT = "DELETE FROM `employees` WHERE (`EMPLOYEE_ID` ='" &
EMPLOYEE_DEL_FRM.DEL_ID_TXT.Text & "'); SELECT * FROM `employees`;"
Use parameterized queries instead, this code is insecure and will choke on single quotes or special characters (try it !). Here is a simple example: FAQ: How do I make a parameterized query in the database with VB.NET?. Please use parameterized queries from now on, don't develop bad habits that will always bite you sooner or later. The security risk alone is too high.
Also I am wondering why you did stacked queries. It would better to separate the SELECT from the DELETE.
In this code variable sql is not needed:
With cmd
sql = SQL_CMD_TXT
.Connection = con
.CommandText = sql
End With
Just use SQL_CMD_TXT directly. Otherwise it makes the code more difficult to follow.

Unwanted name column in DataGridView - How can I get rid of it?

I'm making a WinForms application using VB.NET. I have a DataGridView that I am using to display results of a query to an SQL-Server Database. This works fine:
Dim SQL As New SqlConnection()
Dim CMD As New SqlCommand()
Dim ADP As New SqlDataAdapter()
Dim TBL As New DataTable()
SQL.Close()
SQL.ConnectionString = "Server=" & GetServerIP() & ";Database=" & GetDB() & ";User Id=" & userID & ";Password=" & pass & ";"
CMD.Connection = SQL
CMD.CommandText = "SELECT * FROM " & table
SQL.Open()
ADP.SelectCommand = CMD
TBL.Clear()
ADP.Fill(TBL)
DataGridView1.DataSource = TBL
The issue is that the DataGridView has a column NAME which is empty in every row.
I tried changing the query to SELECT SEQ_NUM FROM CONFIG_SYS that resulted in a DataGridView with a NAME and SEQ_NUM column. I tried calling DataGridView1.Columns.Clear() before the DataGridView1.DataSource = TBL and that does not have an effect on anything. I should mention that if I query any table in my database that does not have a NAME column, I get the same results with an empty NAME column in my DataGridView.
My theory is that a DataGridView automatically adds NAME as the first column, expecting the Database Table to be set up with a NAME column as the primary key. However, my table does not have NAME, it has a column called SEQ_NUM as the primary key. I am able to work around this by doing DataGridView1.Columns("NAME").Visible = False but I don't feel that this is the best way to do it.
Is there a better way to handle this - I'd like the column to not exist at all in the data grid, not just not be visible.
What was causing my issue was the fact that I was calling TBL.Clear() incorrectly.
Calling DataTable.Clear() will clear the Data from a DataTable but it will leave the columns in place.
Instead I should have been calling TBL.Columns.Clear(), which gets rid of the columns of the DataTable. However, using Breakpoints and Visual Studio's DataTable Visualizer I noticed that only calling TBL.Columns.Clear() left the empty rows still in the DataTable. Therefore, to answer the question of how to get rid of a column in a DataGridView that you don't know why/how is there, I suggest to call:
DataTable.Clear()
DataTable.Columns.Clear()
Before setting your DataGridView equal to your DataTable.
Taken from the MSDN:
The .Clear() Method of a DataTable Class "clears the DataTable of all data."
The DataTable.Columns Property gets "a DataColumnCollection that contains the collection of DataColumn objects for the table"
The DataColumnCollection Class also has a .Clear() Method which "clears the collection of any columns."
Thank you #TnTinMn for pointing me in the right direction by using breakpoints and #LarsTech for making me realize that I harshly mixed up DataGridView and DataTable in my original answer.
I hope this post can help others prevent themselves from ripping their hair out about where a non-existent column in their databases seemingly materialized from... If this does not fix your specific issue. I would also check the Query, Database Table setup, and the DataGridView; but for me the issue was with the DataTable.

selecting from one database and inserting row to new database

I'm looking for a pseudo code to write a VB.NET cursor to select columns from one table in one database and inserting it into another table in a different database (they are *not on the same server) using data adapter etc.
I just need something to refer to as I learn. Thanks
Dim selectStr As String = _
"select * from db1"
Dim insertStr As String = _
"insert into db2(col1)"
Try
da_adapter = New OleDb.OleDbDataAdapter(selectStr, connStr)
da2_adapter = New OleDb.OleDbDataAdapter(insertStr, connStr2)
da_adapter.SelectCommand.CommandTimeout = 720
da_adapter.Fill(ds)
da2_adapter.SelectCommand.CommandTimeout = 720
da2_adapter.Fill(ds)
Catch ex As Exception
End Try
In your original code, this part is wrong:
da2_adapter = New OleDb.OleDbDataAdapter(insertStr, connStr2)
When you create a data adapter that way, the SQL statement you provide becomes part of the SelectCommand. You want yours to be part of the InsertCommand, which you need to do yourself:
Dim cmd2 As New OleDb.OleDbCommand(insertStr, connStr2)
da2_adapter = New OleDb.OleDbDataAdapter
da2_adapter.InsertCommand = cmd2
Also, you need to set the AcceptChangesDuringFill property of the first data adapter to False. That way, instead of setting the RowState of all the rows to Unchanged after populating the DataTable, they will remain as Added and ready to be inserted.
You then need to call Update on the second data adapter to save the data rather than calling Fill, which retrieves data.

Perform Action on Each Record from SQLDataSource

I've submitted a bunch of questions as of late - but this has been a great repository of information. I'm a .NET nub, as you can see, so if I'm missing basics or information please let me know and I'll try and fill in the gaps.
I'm using ASP.NET/VB.NET to create this with SQL 2005. I have a project where I'd like to take a set of records from a table, then send each one through an API, get a result and writeback the result to a table, then move to the next.
Initially, my thought was create a SQLDataSource that grabs all the records, then perform the action on a button to do the action of sending through each record.
Is there a way I can call the recordset from SQLDataSource and perform a loop? I'm thinking something like in Classic ASP/VBScript where you would open a RecordSet, do an action, then Loop until the RS was EoF.
Thanks for the help!
You can may want to put your results in a dataset. After getting the results, you can loop through the returned rows
Dim ds As Dataset = GetSomeDataFromSq
For Each dr As DataRow In ds.Tables(0).Rows
Console.WriteLine (dr("ColName"))
Next
You could also use a sqlDataReader
Using conn As sqlconnection = New sqlconnection("put conn info")
Using MyCommand As SqlCommand = New SqlCommand("SELECT ProductName FROM products", conn)
conn.Open()
Using myDataREader As SqlDataReader = MyCommand.ExecuteReader
While myDataREader.Read
Response.Write("Name: " & myDataREader.Item("ProductName"))
End While
End Using
End Using
End Using