how to edit/delete records in a datagridview? - vb.net

I'm using this code for the deleting of records in a datagridview using VB.NET and SQL -12
Private Sub Delete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Delete.Click
If MessageBox.Show("delete this item?", "DELETE!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
Me.DataGridView.Rows.RemoveAt(Me.DataGridView.CurrentRow.)
Else
DataGridView.Update()
End If
End Sub
When I'm using this, the record only gets deleted temporarily but not permanently from the database. How should I delete the records permanently?
The same is the case when I'm editing a field. It's just temporary.

Then you set the deletecommand for the sqldataadapter. The code depends on your table's KeyID name and type, among other things.
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter = New SqlDataAdapter()
...
(here you wrote the dataadapter Fill code)
...
Dim cmdDelete As New SqlCommand("DELETE FROM Customers WHERE KeyID = #KeyID", connection)
cmdDelete.Parameters.Add("#KeyID", SqlDbType.NChar, 8, "KeyID")
adapter.DeleteCommand = command
I think the dataadapter wizard should have done this for you though.

Related

Update database table from DataGridView using DataAdapter

EDIT: This was resolved by querying the table directly rather than by using a stored procedure and ref cursor.
I have a form which only contains a DataGridView dgvDetail. This is the form class code:
Imports Oracle.ManagedDataAccess.Client
Public Class FRM_EditDetail
Dim DataAdapter As New OracleDataAdapter
Dim CommandBuilder As New OracleCommandBuilder(DataAdapter)
Dim Connection As New OracleConnection(connectionString)
Dim Command As OracleCommand = Connection.CreateCommand()
Private Sub FRM_EditDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Connection.Open()
Command.CommandType = CommandType.StoredProcedure
Command.CommandText = "SV_PACKAGE.GetDetail"
Command.Parameters.Add("P_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output
DataAdapter.SelectCommand = Command
DataAdapter.Fill(dsData, "Detail")
dsData.Tables("Detail").PrimaryKey = New DataColumn() {dsData.Tables("Detail").Columns("ID")}
dgvNHHDetail.DataSource = dsData.Tables("Detail")
End Sub
Private Sub FRM_EditDetail_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
CommandBuilder.GetUpdateCommand()
DataAdapter.Update(dsData, "Detail")
Connection.Close()
End Sub
End Class
I want the user to open the form, change the data, and when they close the form the changes are passed into the database table.
The Load event works correctly in so far as dgvDetail is populated from the database table correctly. I get no error on the dsData.Tables("Detail").PrimaryKey = New DataColumn() {dsData.Tables("Detail").Columns("ID")} line, and my database table has a primary key of the same column.
However the FormClosing event triggers, get the Dynamic SQL generation failed. No key information found.
What am I doing wrong with assigning a primary key (or something else)?

Add column to SQL table and populate to datagridview

I have a windows form application with databound datagridview. I want to add column at run time (if user wants to add more column to it). So on button click I wanted to add column. I have added following code to event it adds column in server explorer view under tables column's list but does not show in table definition neither in data source window (in column list under table) nor in datagridview.
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Small_databaseDataSet.newtable' table. You can move, or remove it, as needed.
Me.NewtableTableAdapter.Fill(Me.Small_databaseDataSet.newtable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddColumn()
End Sub
Private Sub AddColumn()
Dim connString As String = "Data Source=(localDb)\ProjectsV13;Initial Catalog=small database;Integrated Security=True"
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Dim str As String = "ALTER TABLE newtable ADD " & TextBoxX1.Text & " INT null;"
Using comm As New SqlCommand(str, conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
End Using
Validate()
DataGridViewX1.Columns.Clear()
NewtableTableAdapter.Update(Small_databaseDataSet.newtable)
NewtableTableAdapter.Fill(Small_databaseDataSet.newtable)
DataGridViewX1.DataSource = NewtableBindingSource
End Sub
End Class
Change this line of code:
' Add the keyword NULL and brackets around the column name
Dim comm As New SqlCommand("ALTER TABLE testTable ADD [col1] INT NULL", conn)
If I wanted to have the new column to show up automatically, I would re-query the database, retrieving the data on that table and just set the datagridview datasource to the resultset like:
'I assume the datagridview name is DataGridView1
DataGridView1.Columns.Clear()
DataGridView1.DataSource = USTDatabaseDataSet
DataGridView1.DataMember = "testTable"
DataGridView1.DataBind()
A DataReader is used to retrieve data. Since there is no data retrieved nothing is loaded into your DataTable except maybe a return value of success or failure. The Using statements ensure that your objects are closed and disposed properly even if there is an error.
Private Sub AddColumn()
Dim connString As String = ConfigurationManager.ConnectionStrings("USTDatabaseConnectionString").ConnectionString
Dim dt As New DataTable
Using conn As New SqlConnection(connString)
Using comm As New SqlCommand("ALTER TABLE testTable ADD col1 INT;", conn)
conn.Open()
comm.ExecuteNonQuery()
End Using
Using com2 As New SqlCommand("Select * From testTable;", conn)
Using reader As SqlDataReader = com2.ExecuteReader
dt.Load(reader)
conn.Close()
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

Changes in Datagridview not saving in table SQLite vb.net

I'm trying to save changes made to datagridview into the table tbl_invent, the changes i make commits to datagridview but it does not save to the table (database), also it doesn't have any error, all i received is a message saying "Records Updated = 0". anyone could point me to the right direction?
Dim da As New SQLiteDataAdapter("select * from tbl_Invent", connection)
Dim ds As New DataSet
'Dim cmdbuilder As New SQLite.SQLiteCommandBuilder(da)
Dim i As Integer
da.TableMappings.Add("tbl_Invent", "tbl_Invent") 'add due to error unable to Update unable to find TableMapping['Table'] or DataTable 'Table'
Try
i = da.Update(ds, "tbl_Invent")
MsgBox("Records Updated= " & i)
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
i already check out this thread:
How to save changes from DataGridView to the database?
-and-
Datagridview save changes to Database vb.net
thank you very much in advance.
It should be obvious that you're not going to save any changes if you don't make any changes between creating/populating your DataTable and trying to save the changes. You need to create the DataTable, populate it and bind it in one method (probably the Load event handler of the form), then the user makes the changes, then you save the changes from the same DataTable in another method (probably the Click event handler of a Button. E.g.
Private table As New DataTable
Private adapter As New SqlDataAdapter("SQL query here", "connection string here")
Private builder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BindingSource1.EndEdit()
adapter.Update(table)
End Sub
The DataTable is created when the form is, the user makes the changes in the grid and clicks the Button and then you save the changes from THE SAME DataTable, not a new one that you just created that contains no changes.

Populate check boxes in DataGridView based on database values vb.net

PLEASE SEE CLEARER EDITED CODE POINTED OUT BELOW TO BE MORE SPECIFIC ON WHERE HELP IS NEEDED.
What I am trying to accomplish is this: I have a DataGridView that is using a DataAdapter to fill with the DataTable. I have hard-coded a separate DataGridViewCheckBoxColumn to come first. The DataGridView columns are as follows (in order):
[0]"ADD" (hard-coded `DataGridViewCheckBoxColumn`)
[1]"Job No" (from sql database)
[2]"Project No" (from sql database)
[3]"Project Name" (from sql database)
I also have a ComboBox populated with usernames from a separate database (but the two have a common key - userId, associating them with which user has admin privileges to edit that particular project in another form). The purpose of this form is to add a project to that user so they can have admin rights to edit additional projects.
I need for the DataGridView to fill with ALL projects, and have the DataGridViewCheckBoxColumn populate '.checked = true' for the projects according to which ones the userId is already associated with having admin privileges (according to existing info in the database). Then I need to have the ability to ADD new projects but checking new checkboxes, then clicking btnUpdate, and updating the database accordingly.
I have been able to populate the DataGridView, create the DataGridViewCheckBoxColumn, make that column NOT readonly, but I can't get it to check the boxes that are associated with the projects, and so on... below is the code... please help?
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'there is where usernames will be filled into dropdown from Proj_users database
Dim fillUName As New SqlCommand("SELECT UName FROM Proj_User WHERE Active = 1 and Admin = 1", frmConnect.DB)
Dim dr As SqlDataReader = fillUName.ExecuteReader()
While dr.Read()
If dr.HasRows = True Then
cmbAddUName.Items.Add(dr("UName"))
End If
End While
dr.Close()
End Sub
Private Sub cmbAddUName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbAddUName.SelectedIndexChanged
Call fillAddGrid(cmbAddUName.Text)
End Sub
Sub fillAddGrid(ByVal PT_User As String)
'column created for checkbox (to be able to check additional projects that will then be added to the user indicated in the combobox's privileges - let's them be able to change that project's details in another form)
Dim chk As New DataGridViewCheckBoxColumn()
grdAddProjectPrivs.Columns.Add(chk)
chk.FalseValue = False
chk.TrueValue = True
chk.HeaderText = "Add"
chk.Name = "Add"
chk.ReadOnly = False
'use stored procedure with parameter to generate recordset
Dim sqlCmd As New SqlCommand
sqlCmd.Connection = frmConnect.DB
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "SP_ManagePrivs"
'IF #SP_Use = 3 -- for ADDING privileges, FILL GRID with ALL projects so can add which ones they need
'BEGIN()
' SELECT
' P.JobNo AS [Job No],
' P.ProjNo AS [Project No],
' P.ProjName AS [Project Name]
' FROM Projects P JOIN User_Projects UP ON P.JobNo = UP.JobNo
' WHERE P.Deleted = 0 and P.Active = 1
' ORDER BY UP.UserID, P.JobNo
'End
'for adding privs, need to show all projects
sqlCmd.Parameters.Add(New SqlParameter("#SP_Use", 3))
sqlCmd.Parameters.Add(New SqlParameter("#UName", DBNull.Value))
sqlCmd.Parameters.Add(New SqlParameter("#Active", DBNull.Value))
sqlCmd.Parameters.Add(New SqlParameter("#Admin", DBNull.Value))
sqlCmd.ExecuteNonQuery()
'use DataAdapter to fill datatable
Dim sqlDA As New SqlDataAdapter()
sqlDA.SelectCommand = sqlCmd
Dim table As New DataTable
sqlDA.Fill(table)
grdAddProjectPrivs.DataSource = table
sqlDA.Dispose()
'reading to get userid to checkboxes accordingly
Dim userID As New SqlCommand("SELECT JobNo FROM User_Projects WHERE PT_User = '" & cmbAddUName.Text & "'", frmConnect.DB)
Dim dr As SqlDataReader = userID.ExecuteReader()
'****THIS IS WHERE I THINK I NEED HELP!!!!
While dr.Read()
If dr.HasRows = True Then
If grdAddProjectPrivs.Columns.Contains(dr("JobNo")) Then
For Each row As DataGridViewRow In grdAddProjectPrivs.Rows
row.Cells("Add").Value = True
Next
End If
End If
End While
dr.Close()
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
'HERE I AM LOOKING TO UPDATE THE DATABASE BY ADDING THE USER'S UserID number TO THAT SPECIFIC PROJECT THAT THEY CHECK OFF WITH THE CHECKBOX.
'i'm thinking once i get the gist of manipulating the checkboxes down pat i can figure this out but if there is anything additional i need to know please advise?
End Sub
End Class
Breakdown of SQL tables' layouts:
USER_PROJECTS TABLE CONSISTS OF (UserID, UserName, JobNo); PROJECTS TABLES CONSISTS OF (UserID, JobNo, ProjNo, ProjName)

How can I have 2 gridviews in one form with same dataset, but other population?

Here you see my code of a form with 2 gridviews. Both have the same dataset, bindingsource. The dataset which is made out of a datasource, has 2 different sql queries.
filld() and fillauswahl() filld shows in the gridview a "select distinct" query.
When the user hits the button1, the selected item from that gridview is saved in "verzeichnis1" this var gets pasted to fillauswahl() which is
select* from mytable where columnx = verzeichnis1
The problem I have is that both gridviews get filled during formload with filld() and by clicking the button with fillverzeichnis() i dont know how to seperate that!? i guess it´s very easy. Cheers and thanks
Public Class Importverzeichnis
Public verzeichnis1 As String
Private Sub Importverzeichnis_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Me.SKM2TableAdapter.Filld(Me.SLXADRIUMDEVDataSet.SKM2)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each cell As DataGridViewCell In DataGridView1.SelectedCells
verzeichnis1 = cell.Value
Next
Me.SKM2TableAdapter.Fillauswahl(Me.SLXADRIUMDEVDataSet.SKM2, verzeichnis1)
End Sub
End Class
Edit: I created a new connection a new datset and new dataadapter and now it works:
Dim connectionString As String = My.Settings.SLXADRIUMDEVConnectionString
Dim sql As String = "SELECT * FROM SKM2 where
Benutzerdefiniert_10 ='" & verzeichnis1 & "' "
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "verzeichnis")
connection.Close()
datagridview2.DataSource = ds
datagridview2.DataMember = "verzeichnis"
but I would be more happy if can use my first dataset and my first adapter. If anyobdy knows how I can do this, I would be happy for the answer
To me the best way would be to just pull down the data as a your normal select statement and then filter the data in your code-behind. By populating a dataset with the same data twice your just making the traffic from the database slower. However, if you wish to keep your current dataset, I would assume that there are two tables in it, one for each select. If that is the case then change:
datagridview2.DataSource = ds
to:
datagridview2.DataSource = ds.Tables(1) 'assumes the second table is used for this datasource