Dataset to a table in database - vb.net

I have a Dataset called 'ds' and I want to put that dataset into one of my tables in my sql database. I cannot seem to find a solution for this. How would I go about putting the dataset into a table? Any help would be greatly appreciated!
Code so far. Dataset that is created from user input:
Dim ds As DataSet = CreateNewDataSet()
Dim entries As New List(Of String())
Console.WriteLine("Enter first name: ")
firstName = Console.ReadLine()
Console.WriteLine("Enter last name: ")
lastName = Console.ReadLine()
entries.Add({firstName, lastName})
entries.ForEach(Sub(x) ds.Tables(0).Rows.Add(x))
I'm only using one table, 'Person' with the fields 'firstname' and 'lastname'.
Trying to insert dataset into table Person:
Using connection = New OleDbConnection("connectionstring")
connection.Open()
Dim adapter = New OleDbDataAdapter()
Dim myQuery As String = String.Empty
myQuery &= "INSERT INTO Applicant (strFirstName, strLastName)"
myQuery &= "VALUES(?, ?)"
adapter.InsertCommand = New OleDbCommand(myQuery, connection)
adapter.InsertCommand.Parameters.AddWithValue("#strFirstName", firstName)
adapter.InsertCommand.Parameters.AddWithValue("#strLastName", lastName)
adapter.Update(ds)
End Using

This is the solution:
Private Function CreateObject(ds as DataSet)
Dim connection as OdbcConnection = new OdbcConnection(conString)
connection.Open()
Dim adapter as OdbcDataAdapter = new OdbcDataAdapter("select * from Table", connection)
ds = new DataSet("DefaultName")
adapter.FillSchema(ds, SchemaType.Source, "Table")
adapter.Fill(ds, "Table")
Dim table as DataTable
table = ds.Tables("Table")
Dim row as DataRow = Nothing
row = table.NewRow()
row("field1") = varField1
row("field2") = varField2
table.Rows.Add(row)
Return ds
End Function

Related

How do I get the value of 'name' col, same way I am getting the rows count?

database name is 'randomTable'
first col name is 'id'
2nd col name is 'name'
How do I get the value of 'name' col, same way I am getting the rows count?
Protected Sub BindGridData()
' Connect to databse and open database file
Dim da As SqlDataAdapter
Dim ds As DataSet = New DataSet()
Dim query As String = "SELECT * FROM [randomTable]"
Dim sqlConn As New SqlConnection(myCon)
Try
sqlConn.Open()
Dim cmd = New SqlCommand(query, myCon)
da = New SqlDataAdapter(cmd)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(da)
da.Fill(ds, "randomTable")
Dim a As Integer = ds.Tables("randomTable").Rows.Count
If a = 0 Then
e.Text = "empty"
End If
'this line is wrong - ???
Dim s As String = ds.Tables("randomTable").Columns("name")
if s = "value1"
'do something
end if
GridView1.DataSource = ds.Tables("randomTable").DefaultView
GridView1.DataBind()
sqlConn.Close()
Catch ex As Exception
End Try
End Sub
If you want the rows Count, you can execute a query tu Database "SElect Count() from randomTable". But in specific what do you want to do?
Either index by a specific row or iterate the row collection e.g.
Dim s As String = ds.Tables("randomTable").Rows(0).Field(Of String)("name")
If s = "value1" Then
'do something
End If
' or
For row As Integer = 0 To ds.Tables("randomTable").Rows.Count
If ds.Tables("randomTable").Rows(row).Field(Of String)("name") = "value1" Then
' do something
End If
Next

Add Column to DataTable before exporting to Excel file

I have a DataTable that is built like this:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Then it is converted to a DataView and exported to Excel like this:
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I want to add another column and fill it with data before I export to Excel. Here's what I'm doing now to add the column:
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
Then to populate it:
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
Dim reader As SqlDataReader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next row
But I get a "System.FormatException: Input string was not in a correct format." error when I run the app. It doesn't seem to like these lines:
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
I think I have more than one issue here because even if I comment out the loop that fills the data in, the column I created doesn't show up in the Excel file. Any help would be much appreciated. Thanks!
EDIT:
Okay, I was grabbing the column name instead of the actual data in the column... because I'm an idiot. The new column still doesn't show up in the exported Excel file. Here's the updated code:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
'set the values of the new column based on info pulled from db
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Dim reader As SqlDataReader
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row.Item(0))
Dim pID As String = row.Item(2).ToString
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
reader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
myConn.Close()
Next row
dt.AcceptChanges()
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I suppose that you want to search your MyTable if it contains a record with the uid and the pid for every row present in your dt table.
If this is your intent then your could write something like this
Dim qry As String = "SELECT UserID FROM [MyTable] WHERE [UserID] = #uid AND [PassID] = #pid"
Using myConn = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Using myCommand = new SqlCommand(qry, myConn)
myConn.Open()
myCommand.Parameters.Add("#uid", OleDbType.Integer)
myCommand.Parameters.Add("#pid", OleDbType.VarWChar)
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row(0))
Dim pID As String = row(1).ToString()
cmd.Parameters("#uid").Value = uID
cmd.Parameters("#pid").Value = pID
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next
End Using
End Using
Of course the exporting to Excel of the DataTable changed with the new column should be done AFTER the add of the column and this code that updates it
In this code the opening of the connection and the creation of the command is done before entering the loop over your rows. The parameterized query holds the new values extracted from your ROWS not from your column names and instead of a more expensive ExecuteReader, just use an ExecuteScalar. If the record is found the ExecuteScalar just returns the UserID instead of a full reader.
The issue was in my CreateExcelFile() method. I inherited the app I'm modifying and assumed the method dynamically read the data in the DataTable and built the spreadsheet. In reality, it was searching the DataTable for specific values and ignored everything else.
2 lines of code later, I'm done.

populate combobox from the selected item of other combobox

I'm creating a form in which a user has to give a State name and a City name. Where the city depends on the state.
Code for populating the city:
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from statestab order by `state` ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
ComboBoxstate.DataSource = ds.Tables(0)
ComboBoxstate.ValueMember = "stateid"
ComboBoxstate.DisplayMember = "state"
Code for the city :
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
Dim st As Integer
st = ComboBoxstate.SelectedValue.ToString()
sql = "SELECT * from citytab where stateid=st order by `cityname` ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
citycombo.DataSource = ds.Tables(0)
citycombo.ValueMember = "cityid"
citycombo.DisplayMember = "cityname"
In the combobox, when the selected city is changed, I call the city load function to populate the city combobox.
But I'm cant populate the city combobox.
You will need handler in Selected_Index_Changed in your State Combobox. From there call your routine to load up the City, in the SQL for city you would need to do
where stateid=" & comboBox1.SelectedValue.ToString()
Here is full text, Note that is can be much better but I tried to keep your syntax in tact:
Private Sub cboState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboState.SelectedIndexChanged
Load_Cities()
End Sub
Private Sub Load_States()
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from tblState order by StateName ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
cboState.DataSource = ds.Tables(0)
cboState.ValueMember = "stateid"
cboState.DisplayMember = "statename"
End Sub
Private Sub Load_Cities()
On Error Resume Next
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT * from tblCity where StateID = " & cboState.SelectedValue.ToString() & " order by CityName ASC;"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, con)
adapter.Fill(ds)
cboCity.DataSource = ds.Tables(0)
cboCity.ValueMember = "CityID"
cboCity.DisplayMember = "CityName"
End Sub

Getting DevExpress Chart Series Values From Array VB.NET

I was trying to set DevExpress Chart Series from Data inside SQL Table.
Everything went fine except that the chart takes only the last attribute from the last series.
My code is:
con.Open() 'it opens SQL Connection
For i = 0 To (CheckedListBoxControl1.CheckedItems.Count - 1) 'list from ListBox
Lst.Add(CheckedListBoxControl1.CheckedItems(i).ToString) 'Putting Data in Array List
Dim Strl As String = String.Format("Select * from VPRogressCumulative where fname like '{0}' and lname like '{1}' order by id, no, CAST('1.' + date AS datetime)", ComboBox1.Text, Lst(i))
Dim sqlCom As New SqlCommand(Strl)
sqlCom.Connection = con
Dim myDA As SqlDataAdapter = New SqlDataAdapter(sqlCom)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "VPRogressCumulative")
ChartControl1.DataSource = myDataSet
ChartControl1.DataAdapter = myDA
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
ser.ArgumentDataMember = "VPRogressCumulative.Date"
ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
Next
con.Close()
I believe my Problem is in:
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
ser.ArgumentDataMember = "VPRogressCumulative.Date"
ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
Last two lines are giving the same series new attributes which I wasn't able to resolve the issue.
Your problem is here:
ChartControl1.DataSource = myDataSet
ChartControl1.DataAdapter = myDA
In each iteration of cycle you are creating the new DataSet and it's overrides previous DataSource in your ChartControl1. Your must use Series.DataSource instead of ChartControl.DataSource. Also you can use DataTable instead of DataSet.
Here is example:
'Your code:
'Dim myDataSet As DataSet = New DataSet()
'myDA.Fill(myDataSet, "VPRogressCumulative")
'ChartControl1.DataSource = myDataSet
'ChartControl1.DataAdapter = myDA
'Replace with this:
Dim myDataTable As DataTable = New DataTable("VPRogressCumulative")
myDA.Fill(myDataTable)
Dim ser As New Series(Lst(i), ViewType.Line)
ChartControl1.Series.Add(ser)
'Your code.
'ser.ArgumentDataMember = "VPRogressCumulative.Date"
'ser.ValueDataMembers.AddRange(New String() {"VPRogressCumulative.Cumulative"})
'Replace with this:
ser.DataSource = myDataTable
ser.ArgumentDataMember = "Date"
ser.ValueDataMembers.AddRange(New String() {"Cumulative"})

DataGridView's RowCount is zero

I am having problems with code below:
For x As Integer = 0 To family_grid.RowCount
family_composition = family_grid.Rows(x).Cells(0).Value
age = family_grid.Rows(x).Cells(1).Value
status = family_grid.Rows(x).Cells(2).Value
relation = family_grid.Rows(x).Cells(3).Value
educational_attainment = family_grid.Rows(x).Cells(4).Value
occupation = family_grid.Rows(x).Cells(5).Value
income = family_grid.Rows(x).Cells(6).Value
dbConnect.Open()
Dim str1 As String = "INSERT INTO tbl_general_intake_family(id, family_composition, age, status, relation, educational_attainment, occupation, income)values(id, family_composition, age, status, relation, educational_attainment, occupation, income)"
Dim da As New OleDbDataAdapter()
Dim ds As New DataSet()
Dim com As New OleDb.OleDbCommand(str1, dbConnect)
com.Parameters.AddWithValue("id", var_document_id)
com.Parameters.AddWithValue("family_composition", family_composition)
com.Parameters.AddWithValue("age", age)
com.Parameters.AddWithValue("status", status)
com.Parameters.AddWithValue("relation", relation)
com.Parameters.AddWithValue("educational_attainment", educational_attainment)
com.Parameters.AddWithValue("occupation", occupation)
com.Parameters.AddWithValue("income", income)
com.ExecuteNonQuery()
com.Dispose()
dbConnect.Close()
Next
The for loop never executes because family_grid.RowCount is returning a value of zero.
In the form_load event, I populate the DataGridView using the following code:
Dim mycon As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" + My.Application.Info.DirectoryPath + "\mswd-rms.mdb")
mycon.Open()
Dim mycomm As New OleDbCommand("SELECT * FROM tbl_general_intake_family WHERE id=" & main_general_intake.document_id, mycon)
Dim da As New OleDbDataAdapter()
da.SelectCommand = mycomm
Dim ds As New DataSet()
da.Fill(ds)
family_grid.Columns.Clear()
family_grid.ReadOnly = true
family_grid.DataSource = ds.Tables(0)
family_grid.Columns(0).HeaderText = "ID"
family_grid.Columns(1).HeaderText = "Name"
family_grid.Columns(2).HeaderText = "Age"
family_grid.Columns(3).HeaderText = "Status"
family_grid.Columns(4).HeaderText = "Relation"
family_grid.Columns(5).HeaderText = "Educational Attainment"
family_grid.Columns(6).HeaderText = "Occupation"
family_grid.Columns(7).HeaderText = "Income"
There is no way the RowCount should be zero given the grid is populated with a single Row in the Form_Load. RowCount should return 1.
To workaround the issue save the datatable to a private form level variable and use its Row.Count.
private dtCurrentGrid As DataTable
..
dtCurrentGrid = ds.Tables(0)
..
For x As Integer = 0 To dtCurrentGrid.Rows.Count