Add column to SQL table and populate to datagridview - sql

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

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)?

Excel to DataGridView with OleDbConnection using two DataAdapter

1- Create C:\Book1.xlsx file into C disk.
2- Ensure that you have one sheet in the C:\Book1.xlsx file named Sheet1.
3- Fill Sheet1 cells from A1 cell to E20 cell with some data.
4- Close C:\Book1.xlsx file.
5- Put one DataGridView into the Form1 and named it as DataGridView1.
6- Run code in order to see if you are able to get excel data to DataGridView correctly.
As you can see I have used two OleDbDataAdapters in order to get excel data to DataGridView.
I have prefer to use two OleDbDataAdapters because I come across out of memory exception if excel data is so big.
If you examine my code you will see that myDataAdapter1 gets excel data from A1 cell to E10 cell.
and myDataAdapter2 supposed to get excel data from A11 cell to E20 cell.
If you examine my code you will see that I tried to merge two DataTables and bind to DataGridView1.DataSource with no success.
Please correct my codes and show me how to merge two DataTables and bind to DataGridView1.DataSource?
I want to get excel data from A1 cell to E20 cell and put the DataGridView1 by using two DataAdapters and two DataTables.
If I use one data adapter then my app crashes with big data.
So I try to use two data adapters and two data tables.
The grid must first add columns to accomadate the data. Then add the rows in a While loop. I only have 3 columns in the test data from Excel.
Private Sub PrepareGrid()
DataGridView1.Columns.Add("col1", "Column 1")
DataGridView1.Columns.Add("col2", "Column 2")
DataGridView1.Columns.Add("col3", "Column 3")
End Sub
Private Sub FillFromExcel()
Dim FileName As String = "Book1.xlsx" '"C:\Book1.xlsx"
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & FileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";")
Using cmd As New OleDbCommand("SELECT * FROM [Sheet1$];", cn)
cn.Open()
Using reader = cmd.ExecuteReader
While reader.Read
DataGridView1.Rows.Add(reader(0), reader(1), reader(2))
End While
End Using
End Using
End Using
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PrepareGrid()
FillFromExcel()
End Sub
DataTable.Merge cannot work without a Primary Key. I fooled around with DataTable.Load(IDataReader) but that must use Merge underneath. So, you can either add a Primary Key to the Excel worksheet (just sort of a row number column) and set the appropriate properties in code or manually loop through the second DataTable adding the records to the grid. (slow)
Here is a slightly different method of filling the grid with all the data. I don't have a large Excel worksheet to test. It might address the memory problems but I am afraid it will use the same methods underneath.
Private Sub FillFromExcel()
Dim FileName As String = "Book1.xlsx" '"C:\Book1.xlsx"
Dim dt As New DataTable
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & FILENAME & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"";")
Using cmd As New OleDbCommand("SELECT * FROM [Sheet1$];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
You can go from an Excel file to a DGV, like this.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
End Class

how to pass multiple values using single textbox in vb.net?

I am doing vb.net programming. In that, I am using one textbox, one gridview and one button. Now, I want to pass queries into the textbox and when clicking on button, I want to display the result into the datagridview.
i.e suppose i am passing selection query and clicking on button at that time i want to display the table data into the datagridview.
I don't know what Db you are using but I have an example using Sql.
Example:
You want to get the Name from the Students Db.
Dim dt As New DataTabale
Dim con As New SqlConnection("connection")
Dim cmd As New OdbcCommand("SELECT * FROM [Students] WHERE [Name] = #Name", con)
con.Open()
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox.Text
dt.Load(cmd.ExecuteReader())
GridView1.DataSource = dt
GridView.DataBind()
You can place this code on Button.
Ps. I view your the edit history of your code and I saw that you are using Db.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim query As String = TextBox1.Text
Try
SqlDataSource1.SelectCommand = query
SqlDataSource1.DataBind()
Catch ex As Exception
MsgBox("No results returned")
End Try
End Sub

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

how to edit/delete records in a datagridview?

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.