DataGridView's RowCount is zero - vb.net

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

Related

Use datagridview cell value from form 1 to filter datagridview 2 in form 2

I have 2 different datagridview (1. Client List 2. Payment History of that Client) in two different forms. When I click the client from form 1 I want to use his clientID to filter the datagridview on Form2 problem is when I use WHERE as a query it doesn't show the table, if I remove WHERE all of the payments in the payment table will show.
here's the code for when clicking the row from form 1
ElseIf colName = "colViewPayment" Then
Dim row As DataGridViewRow = datagridviewClient.Rows(e.RowIndex)
Dim fname As String
Dim lname As String
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM tbtClients WHERE ClientID = #ClientID")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#ClientID", row.Cells("ClientID").Value)
cmd.Connection = con
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
sdr.Read()
fname = sdr("ClientFirstName")
lname = sdr("ClientLastName")
frmLoanerPaymentHistoryBunifu.NameR.Text = fname + " " + lname
frmLoanerPaymentHistoryBunifu.CpNo.Text = sdr("ClientMobileNumber").ToString()
frmLoanerPaymentHistoryBunifu.ClientID.Text = sdr("ClientID").ToString()
End Using
con.Close()
frmLoanerPaymentHistoryBunifu.ShowDialog()
End Using
Here is the code for populating the datagrid in Payment History Form (form2)
Private Sub BindGrid()
Dim CID As String = ClientID.Text
Dim x As Integer = Convert.ToInt64(CID)
Using cmd As New SqlCommand("SELECT * FROM PaymentTable WHERE ClientID = '" + ClientID.Text + "'", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
pDataGrid.AutoGenerateColumns = False
'Add Columns
pDataGrid.Columns(0).Name = "PID"
pDataGrid.Columns(0).DataPropertyName = "PaymentID"
pDataGrid.Columns(1).Name = "CID"
pDataGrid.Columns(1).DataPropertyName = "ClientID"
pDataGrid.Columns(2).Name = "Pdate"
pDataGrid.Columns(2).DataPropertyName = "PDate"
pDataGrid.Columns(3).Name = "Pamt"
pDataGrid.Columns(3).DataPropertyName = "PAmt"
pDataGrid.Columns(4).Name = "Pren"
pDataGrid.Columns(4).DataPropertyName = "ReloanDate"
pDataGrid.Columns(5).Name = "Pcol"
pDataGrid.Columns(5).DataPropertyName = "PColl"
pDataGrid.DataSource = dt
End Using
End Using
End Using
End Sub

Dataset to a table in database

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

The LEVEL clause includes a reserved word or argument that is misspelled or missing, or the punctuation is incorrect vb.net

Dim connstring As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Users\vladut.moraru\Desktop\TCO Orders\02_Template_BOM.xls;Extended Properties=""Excel 8.0;HDR=YES;"""
Dim pram As OleDbParameter
Dim dr As DataRow
Dim olecon As OleDbConnection
Dim olecomm As OleDbCommand
Dim olecomm1 As OleDbCommand
Dim oleadpt As OleDbDataAdapter
Dim ds As DataSet
Try
olecon = New OleDbConnection
olecon.ConnectionString = connstring
olecomm = New OleDbCommand
olecomm.CommandText = "Select Level, F_N, Name, Rev from [BOM$]"
olecomm.Connection = olecon
olecomm1 = New OleDbCommand
olecomm1.CommandText = "Insert into [BOM$] " & "(Level, F_N, Name, Rev) values " & "(#FName, #LName, #Age, #Phone)"
olecomm1.Connection = olecon
pram = olecomm1.Parameters.Add("#FName", OleDbType.VarChar)
pram.SourceColumn = "Level"
pram = olecomm1.Parameters.Add("#LName", OleDbType.VarChar)
pram.SourceColumn = "F_N"
pram = olecomm1.Parameters.Add("#Age", OleDbType.VarChar)
pram.SourceColumn = "Name"
pram = olecomm1.Parameters.Add("#Phone", OleDbType.VarChar)
pram.SourceColumn = "Rev"
oleadpt = New OleDbDataAdapter(olecomm)
ds = New DataSet
olecon.Open()
oleadpt.Fill(ds, "BOM")
If IsNothing(ds) = False Then
dr = ds.Tables(0).NewRow
dr("Level") = "Raman"
dr("F_N") = "Tayal"
dr("Name") = 24
dr("Rev") = 98989898
ds.Tables(0).Rows.Add(dr)
oleadpt = New OleDbDataAdapter
oleadpt.InsertCommand = olecomm1
Dim i As Integer = oleadpt.Update(ds, "BOM")
End If
Catch ex As Exception
Finally
olecon.Close()
olecon = Nothing
olecomm = Nothing
oleadpt = Nothing
ds = Nothing
dr = Nothing
pram = Nothing
End Try
I want tot write into tamplate excel with column Level, F_N, Name, Rev and my code generate that error from title. I want to insert some value in my excel but on line oleadpt.Fill(ds, "BOM") give me that error. I put a pic with excel file. The sheet name is BOM
My question is, where i miss to generate that code? I write wrong my columns or my connection?

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