DataSet, DataAdapter, no dataTable Primary key - vb.net

Ok so I'm having this:
Dim sql As String = "SELECT * FROM Articles"
dAdapter = New OleDbDataAdapter(sql, connection)
dSet = New DataSet("tempDatatable")
With connection
.Open()
dAdapter.Fill(dSet, "Articles_table")
.Close()
End With
With DataGridView1
.DataSource = dSet
.DataMember = "Articles_table"
End With
And I wonder if there is any possible way to define the first column as the primary key. I've looked around but everyone is using a manual datatable to fill up the datagrid. Since I'm using a dataBase I don't know how to set a primary key from there. I need some help.

You have to set the DataAdapter's MissingSchemaAction to AddWithKey:
var table = new DataTable();
using(var con = new SqlConnection(connectionString))
using (var da = new SqlDataAdapter("SELECT * FROM Articles", con))
{
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.Fill(table);
}
Edit: VB.NET:
Dim table = New DataTable()
Using con = New SqlConnection(connectionString)
Using da = New SqlDataAdapter("SELECT * FROM Articles", con)
da.MissingSchemaAction = MissingSchemaAction.AddWithKey
da.Fill(table)
End Using
End Using
Now the necessary columns and primary key information to complete the schema are automaticaly added to the DataTable.
Read: Populating a DataSet from a DataAdapter

You can add a primary key to your data table using something like this:
var table = dSet.Tables["Articles_table"];
table.PrimaryKey = new DataColumn[] { table.Columns[0] };
Sorry, just realised the question was tagged with vb.net, not c#. VB.net would be:
Dim table = dSet.Tables("Articles_table")
table.PrimaryKey = New DataColumn() {table.Columns(0)}

Please do it like this.
Dim objTmpTable As New DataTable
objTmpTable.PrimaryKey = New DataColumn() {objTmpTable.Columns(0)}
dgrdMeasure.DataSource = objTmpTable
dgrdMeasure.DataBind()
That is, before assigning to Grid, just set the Primary key.

Related

VB.NET Updating database table using dataset

I am trying to update my physical database using a dataset. There is no error that appears but the Table in my Database doesn't updating at all.
I am using VS 2012, VB.NET
This is my code for updating my database table name "ProdRec"
grid()
Dim da As New OleDbDataAdapter
Dim cb As New OleDb.OleDbCommandBuilder(da)
da.Update(ds, "ProdRec")
ds.AcceptChanges()
I declare my dataset named "ds" in this Public sub
Public Sub grid()
connect()
MD = "Select * From ProdRec"
com = New OleDbCommand(MD, conn)
adaptr = New OleDbDataAdapter(com)
ds = New DataSet
adaptr.Fill(ds, "ProdRec")
With DataGridView1()
.DataSource = ds
.DataMember = "ProdRec"
End With
End Sub
Try to add this before da.Update command: da.UpdateCommand = cb.GetUpdateCommand()

Is filling a DataTable necessary for just setting variables with 2 column values?

I am trying to improve performance of an application, I have a case where a common SPROC is being used but is it necessary to fill a DataTable just to set 2 variable values?
Is there anything more efficient?
Dim Conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
Dim CmdUsers As SqlCommand = New SqlCommand("uspGetUsers", Conn)
CmdUsers.CommandType = CommandType.StoredProcedure
CmdUsers.Parameters.Add(New SqlParameter("#UserName", Session("UserID")))
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim dtUserInfo As DataTable = New DataTable
da = New SqlDataAdapter(CmdUsers)
da.Fill(dtUserInfo)
isParent = dtUserInfo.Rows(0)("IsAdmin")
UserVal = dtUserInfo.Rows(0)("UserVal")
A SqlDataReader is the fastest way to read data from a query. Try the following:
Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("DB").ConnectionString)
conn.Open()
Using cmd As New SqlCommand("uspGetUsers", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#UserName", Session("UserID"))
Using reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
isParent = reader("IsAdmin")
UserVal = reader("UserVal")
End While
End Using
End Using
End Using
You may need to parse the data to the correct types.
Also, note the use of Using to automatically dispose of the connection, command and reader objects: http://msdn.microsoft.com/en-GB/library/htd05whh.aspx

Linking two DataGridViews

I have two Grid controls in VB.Net Winform application connected to Oracle Database. The first one shows a table 1 with fields (among others) ID and TaskName. The second one shows a linked table with fields (among others) Task. In the logic of the application the two tables are linked (Table 1, Field ID) <----> (Table 2, Field Task).
I would like, when selecting a row in the first DataGridView, have only the linked row in the second GridView but I can't make it work.
Here is my code attempt :
Dim SQLQuery As String = "SELECT * FROM SCHEME.ARCH_TASKS"
Conn = New OracleConnection(ConnectionString)
Command = New OracleCommand(SQLQuery, Conn)
DataAdapter = New OracleDataAdapter(Command)
DataSet = New DataSet()
DataTable1 = New DataTable
DataSet.Tables.Add(DataTable1)
DataAdapter.Fill(DataTable1)
DataGridView.DataSource = DataTable1.DefaultView
GridControl1.DataSource = DataTable1.DefaultView
SQLQuery = "SELECT * FROM SCHEME.ARCH_LINK_ROLE_TASK"
Command = New OracleCommand(SQLQuery, Conn)
DataAdapter = New OracleDataAdapter(Command)
DataTable2 = New DataTable
DataSet.Tables.Add(DataTable2)
DataAdapter.Fill(DataTable2)
GridControl2.DataSource = DataTable2
DataSet.Relations.Add(DataTable1.Columns("ID"), DataTable2.Columns("TASK"))
Here is the result
http://img11.hostingpics.net/pics/4713062013102413h1253.png
As you can see, I added manually a relationship between the two data tables but it doesn't really do what i'm looking for. It simply adds a subline in the first grid control.
http://img11.hostingpics.net/pics/7508382013102413h1309.png
I tried to apply what PeterG suggested but I still can't make it work.
Dim SQLQuery As String = "SELECT * FROM SCHEME.ARCH_TASKS"
Command = New OracleCommand(SQLQuery, Conn)
DataAdapter = New OracleDataAdapter(Command)
DataSet.Tables.Add(DataTable1)
DataAdapter.Fill(DataTable1)
SQLQuery = "SELECT * FROM SCHEME.ARCH_LINK_ROLE_TASK"
Command = New OracleCommand(SQLQuery, Conn)
DataAdapter = New OracleDataAdapter(Command)
DataSet.Tables.Add(DataTable2)
DataAdapter.Fill(DataTable2)
DataSet.Relations.Add(DataTable1.Columns("ID"), DataTable2.Columns("TASK"))
BindingSource1.DataSource = DataSet
GridControl1.DataSource = BindingSource1.DataSource
GridControl1.DataMember = "Table1"
BindingSource2.DataSource = BindingSource1.DataSource
GridControl2.DataSource = BindingSource2.DataSource
GridControl2.DataMember = "Table2"
Am I missing something ?
Thank you.

Populating and editing datagrid from a SQL Server table

I need to populate my datagrid from my a table in SQL Server called Pastel_Companies and then if any changes are made to the datagrid it has to update it to the database.
I am using a default view to populate my datagrid.
Is there another way where I link each column separately so I can resize my columns as they are fixed to what SQL has?
Here is my code:
Dim cn As New SqlClient.SqlConnection(SQL_Loader("", My.Settings.SQL_Win_Auth, My.Settings.SQL_Username, My.Settings.SQL_Password, My.Settings.SQL_Server_Name, My.Settings.SQL_DB_Name))
Dim Cmd As New SqlClient.SqlCommand
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New SqlClient.SqlDataAdapter
Cmd.Connection = cn
cn.Open()
da = New SqlClient.SqlDataAdapter("Select Company_ID, Prefix, DSN, File_Path From Pastel_Companies", cn)
da.Fill(dt)
'DataGridView1.Columns.Add("Company_ID", Prefix.ToString)
DataGridView1.DataSource = dt.DefaultView
cn.Close()
From: http://social.msdn.microsoft.com/Forums/windows/en-US/e444ca84-3319-4dfa-aa31-46f310dd0c13/datagridview-autosize-rowcolumn
'for the rows
DataGridView1.AutoResizeRow(2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader)
'and for columns
DataGridView1.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
or you can use for each loop
DataGridView1.Columns(i).Width = x

Saving record with dataset

I want to save a record in the database using a dataset, but my data is not committing into my database.
My code can be viewed below:
Dim mydataset1 As New MyDataSet
Dim row As DataRow = mydataset1.Tables("testtable").NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
mydataset1.Tables("testtable").Rows.Add(row)
Any help will be appreciated
A DataSet/DataTable is a offline/in-memory representation of your database. If you want to update the database, you need to use a DataAdapter.
For example (assuming you're using MS-Sql-Server):
Public Function UpdateDataSet(dataSet As DataSet) As Int32
Using con = New SqlConnection(My.Settings.SqlConnection)
Dim sql = "INSERT INTO TUser(Name,Address)VALUES(#Name,#Address)"
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
cmd.Parameters.Add(New SqlParameter("#Address", SqlDbType.VarChar))
Using da = New SqlDataAdapter()
da.InsertCommand = cmd
con.Open()
Dim rowCount = da.Update(dataSet)
Return rowCount
End Using
End Using
End Using
End Function
I could be rusty here since its a long time since I wrote any VB.NET or used data adapters/datasets/datatables but I think if you decide to take that route you would need code like this:
Dim connection As New SqlConnection("#####YourConnectionString#####")
connection.Open()
Dim adapter As New SqlDataAdapter("SELECT * FROM testtable", connection)
' For the line below to work, you must have a primary key field in "testtable"
Dim builder As New SqlCommandBuilder(adapter)
Dim testtable As New DataTable("testtable")
adapter.Fill(testtable)
Dim row As DataRow = testtable.NewRow()
With row
.Item("name") = "Segun Omotayo"
.Item("address") = "Abuja"
End With
testtable.Rows.Add(row)
adapter.Update(testtable)
connection.Close()