delete selected rowdata in datatable vb - vb.net

Hey guys how to delete data on datatable
my code where i delete data and the result just remove data from grid not datatable
my current code
selectStr = "AccrualNo = '" & bauAccrual & "' AND GLAccountID = '" & bauGL &"' AND PCCodeID = '" & bauPC & "'"
rowToDelete = TempTable.Select(selectStr)(0)
rowToDelete.Delete
TempTable.AcceptChanges
BAU_grdTransactions.DataSource = TempTable

Try this:
string selectStr = "primary_key =" + pk
DataRow rowToDelete = dataTable.Select(selectStr)(0)
dataTable.Rows.Remove(rowToDelete)
primary_key is the Primary Key of your data table. pk value you can extract from the GridView. if pk is string, use in single quotes.

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

Represent field in DB by variable

I have a project which is linked with a MDB file. I need to filter records of a table based on a condition, and both "field name" and the value or conditions should be passed to a Sub via variables. The select statement doesn't work. Did I miss something?
Dim Result() As DataRow
Dim strField As String = "asset_code"
Dim dblValue As Double = 3
Dim tblName as Datatable = AssetsDataSet.Assets
Result = tblName.Select(" '" & strField & "' = '" & dblValue& "' ")
I suspect that you need to loose the single quotes around the field name and as the data because it looks like it is numeric:
Result = tblName.Select(strField & " = " & cstr(dblValue) )
With string data you need to use a function:
Result = tblName.Select("textfield = " & cSQL(StringData) )
Function cSQL(psTextData As String) As String
' Replace any single quotes to be 2 single quotes
Return "'" + Replace(psTextData, "'", "''") + "'"
End Function

How to put a concatenated data from database to a label

My table goes like this:
| ID | FNAME | LNAME |
My code goes like this:
cmd.CommandText = "SELECT * FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("CONCAT(fname,' ',lname)").ToString()
cmd.CommandText = "SELECT CONCAT(fname,' ',lname) FROM members WHERE ID = '" & Label18.Text & "';"
Label3.Text = cmd.ExecuteScalar
Note : This makes sense when the select returns a single Cell value
ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or
Stored Procedure and returned a scalar value on first column of first
row in the Result Set. If the Result Set contains more than one
columns or rows , it takes only the first column of first row, all
other values will ignore. If the Result Set is empty it will return a
Null reference.
The easiest way is to just return an additional column from the database itself.
cmd.CommandText = "SELECT *, FullName = fname + ' ' + lname FROM members WHERE ID = '" & Label18.Text & "'"
dreader = cmd.ExecuteReader()
dreader.Read()
Label3.Text = dreader("FullName").ToString()

Can't insert into acces db with .net

I used this site to get me on my way with the Insert command, however, i can't get it to work.
How can I insert data into 2 different table in VB.net, I'm using MS Access as my db
I got 3 tables, 1 with foodtypes, 1 with (basically) menus and 1 connecting table that connect the id of a menu with the ID's of sfoodtypes.
I try to use a query to create new menu's. however, a error occures:
There is ; missing in the sql string
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Now, i tried different places to place the ; but cant find the right spot. Can anyone help me?
The rest of the code::
EDIT:(and clean-up)
I made some changes based on the comments below, but i still get the ; missing error.
Dim cmd As New OleDbCommand
Dim cmd1 As New OleDbCommand
Dim cmd2 As New OleDbCommand
Dim Str As String
Dim Str1 As String
Dim Str2 As String
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text) VALUES (cbRantsoen.text, cbVoer.text, txtGewicht.text); " 'WHERE RantsoenID = tblRantsoen.RantsoenID, Voer = '" & cbVoer.Text & "', Gewicht = '" & tbGewicht.Text & "'"
Str1 = "INSERT INTO tbl_voersoorten (VoerID, Voer) VALUES (cbVoer.text) WHERE Voer = '" & cbVoer.Text & "'"
Str2 = "INSERT INTO tbl_rantsoenKoppel (VoerID, RantsoenID) VALUES() WHERE RantsoenID = tbl_rantsoenkoppel.FKRantsoenID AND VoerID = tbl_voersoorten.VoerID"
connection.Open()
cmd = New OleDbCommand(Str, connection)
cmd1 = New OleDbCommand(Str1, connection)
cmd2 = New OleDbCommand(Str2, connection)
cmd.ExecuteNonQuery()
cmd1.ExecuteNonQuery()
cmd2.ExecuteNonQuery()
You can't use WHERE clauses in your INSERT command
and if you want execute more than one command in single CommandTextyou should to seperate them with ;.
and finally:
Str = "INSERT INTO tbl_rantsoen (Rantsoen, Voer, Gewicht) VALUES ('" & cbRantsoen.text & "', '"& cbVoer.text & "','"& txtGewicht.text & "')"
Str1 = "INSERT INTO tbl_voersoorten ( Voer) VALUES ('" & cbVoer.text & "')"
and for query Str3 you should to get related id from last two query and insert them into 3th query ;)
Your INSERT Syntax is wrong. There cannot be a WHERE Clause.
INSERT INTO TableName (Column1,Column2,Colum3) VALUES(Value1,Value2,Value3);
If you are trying to change an existing record, try using the UPDATE Clause
UPDATE TableName SET Column1 = Value1 , Column2 = Value2, Column3 = Value3 WHERE Condition1 = Condition2 AND Condition3 = Condition4

Selecting table depends on textbox value

I just created a table programmatically. I named it as my Textbox value.
Example:
Create table " & Textbox1.text & " + ......
I want to set my table name according to my Textbox value.
Select TaskNumber,Name,Age From '" & Textbox1.text & "' "
The best pratice would be to put your textbox value in a variable:
Dim myTableName As String
myTableName = TexBox1.text
// SQL Connection
Dim conStr As String = "Server=MyServer;Database=Mydatabase;Trusted_Connection = yes"
Dim objCon As New SqlConnection(conStr)
Dim obj As SqlCommand
Dim strSQL as String
obj = objConn.CreateCommand()
// *************** Select statement *********
strSQL = "SELECT TaskNumber, Name, Age FROM " & myTableName
// **************** Create statement *********
strSQL = "CREATE TABLE " & myTableName & "(" & _
"Id int NOT NULL PRIMARY KEY IDENTITY, " & _
"ColumnTest VARCHAR(30)) "
// Execute the command
obj.CommandText = strSQL
obj.ExecuteNonQuery()
Try this:
Dim query AS String = "Select TaskNumber,Name,Age From " & Textbox1.Text.Trim().Replace("'","")
.Replace("'","") will prevent SQL-Injection attack due to the presence of single quotes in the TextBox text.
I will suggest you using RegularExpressionValidator on your TextBox to limit the allowed characters.