How to display data in a datagrid - sql-server

I have a class name cal.class. the function perform a loan calculation. it read the interest rate from a database and perform the calculation based on the amount input. I want to display the result in a data grid. for e.g InterestRate, MonthlyPayment, TotalPayment. I don't know how to do it.
Below is what I have I tried:
Cal.class
Public Shared Sub Calculator(ByVal _Source As String, ByVal _LoanAmount As Double, ByVal _LoanType As String,ByVal _Years As Double)
Dim myCommand As New SqlCommand
Dim SConn As String = ClsConnStr.GetConnString(_Source)
Using conn As New SqlConnection(SConn)
Dim MonthlyPayment As Double
Dim MonthlyInterestRate As Double
Dim TotalPayment As Double
conn.Open()
myCommand.Connection = conn
Dim daReader As SqlDataReader
Dim Sql As String = "Select Interestrate AS RESULT from tblloan where LoanType = '" & _LoanType & "'"
Dim scmd As New SqlCommand(Sql, conn)
daReader = scmd.ExecuteReader()
If daReader.HasRows Then
While daReader.Read()
MonthlyInterestRate = (daReader("RESULT")) / 1200
MonthlyPayment = _LoanAmount * MonthlyInterestRate / (1 - 1 / Math.Pow(1 + MonthlyInterestRate, _Years * 12))
TotalPayment = MonthlyPayment * _Years * 12
End While
End If
conn.Close()
End Using
End Sub
I call the method: cal.Calculator("TEST", "5000", "FS", "5")
and I have a data grid in my form.

Create a DataTable with the column headers and datatypes you need.
Include your command in the Using...End Using block. You can pass your connection string directly to the constructor of the connection. Also, you can pass the command text and the connection to the constructor of the command.
Add rows to the DataTable in the While loop
Public Shared Function Calculator(ByVal _Source As String, ByVal _LoanAmount As Double, ByVal _LoanType As String, ByVal _Years As Double) As DataTable
Dim dt As New DataTable
dt.Columns.Add("Monthly Interest Rate", GetType(Decimal))
dt.Columns.Add("Monthly Payment", GetType(Decimal))
dt.Columns.Add("Total Payment", GetType(Decimal))
Dim SConn As String = ClsConnStr.GetConnString(_Source)
Using conn As New SqlConnection(SConn),
myCommand As New SqlCommand("Select Interestrate AS RESULT from tblloan where LoanType = #LoanType", conn)
myCommand.Parameters.Add("#LoanType", SqlDbType.VarChar).Value = _LoanType
conn.Open()
Using daReader = myCommand.ExecuteReader
If daReader.HasRows Then
While daReader.Read()
Dim col1 = CDbl(daReader("RESULT")) / 1200
Dim col2 = _LoanAmount * col1 / (1 - 1 / Math.Pow(1 + col1, _Years * 12))
Dim col3 = col2 * _Years * 12
dt.Rows.Add({CDec(col1), CDec(col2), CDec(col3)})
End While
End If
End Using
End Using
Return dt
End Function
Your call parameters are wrong. You cannot pass a Double as a String (enclosed in quote)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = Calculator("TEST", 5000, "FS", 5)
'You will probably have to add formatting to the grid
DataGridView1.DataSource = dt
End Sub

Related

Search by specific date in Access database with VB.net

I'm trying to search a date using DateTimePicker in an Access database and have the results show in the DataGridView but it doesn't work. No errors but it just doesn't show the database/results. Here's pictures of the database and the debugged form when it doesn't work in case they are of any use:
and here's my code:
Imports System.Data.OleDb
Public Class Form10
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Sales.accdb;")
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim dt1 As DateTime = DateTime.Parse(DateTimePicker1.Value)
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("MM/dd/yyyy"), connection)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
DataGridView2.DataSource = da
connection.Close()
End Sub
Private Sub Form10_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "MM/dd/yyyy"
End Sub
End Class
Use the true date value of the datetime picker:
Dim dt1 As DateTime = DateTimePicker1.Value
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Table1] where [TDateField] = #" & dt1.ToString("yyyy'/'MM'/'dd") & "#", connection)

Auto generate alpha numeric in VB.NET

I'm currently working on my project for which I used VB.NET 2019 and SQL server. I need to create a function which auto generates IDs.
I want my IDs to be like these: P001, P002, P003 etc. Can someone show me how to code it? Below is my code
Private Sub Form4_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
BindData()
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If Con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select Max(PatientID) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If Max > 0 Then
TextBox1.Text = Max + 1
Else
TextBox1.Text = "P01"
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
You can try like this. Here 1 is an auto-generated number that may be an identity key column value from a table in SQL Server.
Dim number As Integer = 1
Dim numberText As String = "P" & number.ToString().PadLeft(3, "0")
Live demo
You can add a computed column like this in your table for auto-generating the sequences. This will reduce the chances of duplicate value runtime once more than one person will do the entry simultaneously.
Alter table Patient ADD PatientCode AS ('P' + Convert(Varchar(3),CONCAT(REPLICATE('0', 3 - LEN(PatientID)), PatientID)) )
To get the column value dynamically you can try the below code to generate function.
Private Sub GenerateSequnce()
Dim constring As String = "Data Source=TestServer;Initial Catalog=TestDB;User id = TestUser;password=test#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("Select Top 1 ISNULL(TaxCode, 0) from Tax_Mst Order By TaxCode Desc", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
Dim maxNumberCode = dt.Rows(0)("TaxCode").ToString()
If (maxNumberCode = "0") Then
maxNumberCode = "1"
End If
Dim numberText As String = "P" & maxNumberCode.ToString().PadLeft(3, "0")
End Using
End Using
End Using
End Using
End Sub
Here the column TaxCode is int with identity constraint.
With the minor correction in your code, you can achieve this as shown below.
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select ISNULL(Max(PatientID), 0) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If (Max = "0") Then
Max = "1"
Else
Max = CInt(Max) + 1
End If
Dim numberText As String = "P" & Max.ToString().PadLeft(3, "0")
TextBox1.Text = numberText
Catch ex As Exception
MsgBox(Err.Description)
End Try
OUTPUT

import excel in datagrid view vb.net

I'm trying to import Excel in datagridview using this methods in the code below. But I have an error in this line "invalidOperationException" can't get the data to show up
cnnExcel.Open()
and here is the whole code
comboBox as cmbExcel
Having some if condition for supporting depend on excel version (2003 - 2013)
Imports System.Data.OleDb
Public Class Form1
Dim cnnExcel As New OleDbConnection
Public Function GetExccelSheetNames() As String()
Dim ConStr As String = ""
Dim dt As DataTable = Nothing
Dim opExcel As New OpenFileDialog
opExcel.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls"
opExcel.ShowDialog()
Dim pathExcel As String = opExcel.FileName
If pathExcel.Trim = "" Then
MessageBox.Show("Please Select Excel File !")
Return Nothing
Else
Dim Ext As String = pathExcel.Substring(pathExcel.LastIndexOf(".") + 1)
If Ext.Length = 3 Then
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"
ElseIf Ext.Length = 4 Then
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=YES';"
End If
cnnExcel = New OleDbConnection(ConStr)
cnnExcel.Open()
dt = cnnExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheetNames As [String]() = New [String](dt.Rows.Count - 1) {}
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheetNames(i) = row("TABLE_NAME").ToString()
i += 1
Next
cnnExcel.Close()
Return excelSheetNames
End If
End Function
Added a Button as btnBrows to brows excel file from any location in local drive
Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click
cmbsheet.DataSource = GetExccelSheetNames()
End Sub
Dim dt As New DataTable
Then Finally having a button to view the excel in datagridview
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim cmd As New OleDbCommand("Select * from [" + cmbsheet.SelectedValue.ToString() + "]", cnnExcel)
cnnExcel.Open()
dt.Clear()
dt.Load(cmd.ExecuteReader())
cnnExcel.Close()
DataGridView1.DataSource = dt
End Sub
End Class
Use this as a reference. It's 100% working. I'm using this in one of my applications. Put this code on your import button.
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
Dim path As String = OpenFileDialog1.FileName
Me.TextBox1.Text = path.ToString
Try
Me.dgvFile.DataSource = Nothing
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Me.TextBox1.Text & "';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.DataTable
MyCommand.Fill(DtSet)
Me.dgvFile.DataSource = DtSet
MyConnection.Close()
MessageBox.Show("File successfully imported")
Catch ex As Exception
MessageBox.Show("Error")
End Try

How to prevent array from adding (sum) together

I have an array. My program goes through and sets up the array. However, when I display the array,it's adding the arrays together.
Here is my code:
Public Class frmMain
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim yPoint As Integer
Dim LocationDB As String
Dim dtstartdate As Date
Dim dtenddate As Date
Dim LocationName As String
Dim BookSales(17) As Integer
Public Shared locationcounter As Integer
Dim i As Integer
Public Sub Get_Info()
If locationcounter < 18 Then
dtstartdate = dtpStartDate.Value
dtenddate = dtpEndDate.Value.AddDays(1).AddSeconds(-1)
Try
connetionString = "Data Source=" & LocationDB & ";Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=test"
sql = "Select * from fGetdata"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.SelectCommand.CommandTimeout = 130
adapter.SelectCommand.Parameters.AddWithValue("#StartDate", dtstartdate)
adapter.SelectCommand.Parameters.AddWithValue("#EndDate", dtenddate)
adapter.Fill(ds)
connection.Close()
connection.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
For Each FoundRow As DataRow In ds.Tables(0).Rows
Select Case FoundRow("CategoryName")
Case "TOTAL"
Select Case FoundRow("Description")
Case "BOOK", "BOOK SALES", "GC"
BookSales(i) = BookSales(i) + (FoundRow("netAmt"))
End Select
End Select
Next
MsgBox(LocationName & BookSales(i))
MsgBox(LocationName & BookSales(0))
MsgBox(LocationName & BookSales(1))
End If
End Sub
Public Sub GetLocation()
Select Case locationcounter
Case "1"
LocationName = "Location1"
Locationdb = "10.0.1.52"
Case "2"
LocationName = "Location2"
Locationdb = "10.0.1.51"
Case "3"
LocationName = "Location3"
Locationdb = "10.0.1.50"
End Select
End Sub
Button Click:
For x = 1 To 3
GetLocation()
Label1.Text = LocationName
Label1.Refresh()
Get_Info()
i = i + 1
locationcounter = locationcounter + 1
Next
I am getting:
Location1 5
Location2 25
Location3 35
I would like to get:
Location1 5
Location2 20
Location3 10
For some reason the arrays are adding together
As you noted, the problem is that the DataSet was getting reused so it accumulated the results on each loop.
You need to clean up the coding style. Put things in as tight of scope as possible. In this case all the vars used by the Get_Info() method should be declared within the method. This prevents side effects from long living variables. The DataSet is only used in the Get_Info method so it should only exist there.
Clean up the resources in a Finally block. In the example below I moved the connection.Dispose into the finally block. You only need to call Dispose, you don't need the Close also.
You should also enable Option Strict and Option Explicit. These will help prevent casing errors that don't show up until runtime. As an example of type mismatch, you declare the loctioncounter as integer but use it as a string in the GetLocation method.
There are more but this should get you started in the right direction.
Public Class frmMain
Dim yPoint As Integer
Dim LocationDB As String
Dim dtstartdate As Date
Dim dtenddate As Date
Dim LocationName As String
Dim BookSales(17) As Integer
Public Shared locationcounter As Integer
Dim i As Integer
Public Sub Get_Info()
Dim connetionString As String
Dim connection As SqlConnection = Nothing
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
If locationcounter < 18 Then
dtstartdate = dtpStartDate.Value
dtenddate = dtpEndDate.Value.AddDays(1).AddSeconds(-1)
Try
connetionString = "Data Source=" & LocationDB & ";Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=test"
sql = "Select * from fGetdata"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.SelectCommand.CommandTimeout = 130
adapter.SelectCommand.Parameters.AddWithValue("#StartDate", dtstartdate)
adapter.SelectCommand.Parameters.AddWithValue("#EndDate", dtenddate)
adapter.Fill(ds)
For Each FoundRow As DataRow In ds.Tables(0).Rows
Select Case FoundRow("CategoryName")
Case "TOTAL"
Select Case FoundRow("Description")
Case "BOOK", "BOOK SALES", "GC"
BookSales(i) = BookSales(i) + (FoundRow("netAmt"))
End Select
End Select
Next
MsgBox(LocationName & BookSales(i))
MsgBox(LocationName & BookSales(0))
MsgBox(LocationName & BookSales(1))
Catch ex As Exception
MsgBox(ex.Message)
Finally
If connection IsNot Nothing Then
connection.Dispose()
End If
End Try
End If
End Sub
Public Sub GetLocation()
Select Case locationcounter
Case "1"
LocationName = "Location1"
LocationDB = "10.0.1.52"
Case "2"
LocationName = "Location2"
LocationDB = "10.0.1.51"
Case "3"
LocationName = "Location3"
LocationDB = "10.0.1.50"
End Select
End Sub

column does not belong to table Table

I don't know exactly where I have to look for.
Error is:
Column 'pkJudge' does not belong to table Table. '
at System.Data.DataRow.GetDataColumn(String columnName)
at System.Data.DataRow.set_Item(String columnName, Object value)
at ReadyCollect.CaseEntry.S_GetJudges(Int32 courtID)
at ReadyCollect.CaseEntry.S_GetExistCaseInfo()
at ReadyCollect.CaseEntry.CaseReminder_HoldCase()
at ReadyCollect.CaseEntry.btnSave_Click(Object sender, EventArgs e)
It occurs in the following code fragment. Any Ideas?
Private Sub S_GetJudges(ByVal courtID As Integer)
' Load the list of judges '
Dim JudgeSet As New DataSet
Dim dv As System.Data.DataView
Dim DAl As New DataAccessLayer
Dim pfkCourt As Integer = CourtDDL.SelectedValue
If ClientKey > 0 And pfkCourt > 0 Then
JudgeSet = DAl.GetJudgespkJudgesJudgeNamefkCourt(ClientKey, pfkCourt)
JudgeDataTable = JudgeSet.Tables(0)
Dim dr As System.Data.DataRow
dr = JudgeDataTable.NewRow()
dr("pkJudge") = "0"
dr("Judge Name") = "(Select a Judge)"
JudgeDataTable.Rows.Add(dr)
JudgeDDL.SelectedValue = 0
JudgeDDL.DataSource = JudgeDataTable.DefaultView
dv = JudgeDataTable.DefaultView
dv.Sort ="pkJudge ASC"
JudgeDDL.DataBind()
End If
End Sub
And the dataaccess method that is called in the code fragment is below.
Now JudgeDataTable is declared as
Private JudgeDataTable As System.Data.DataTable on top of the page.
Rest is in the code fragment as I posted above.
'Retreives fields pkJudge and [Judge Name] from the table Judges where field fkCourt is equal to fkCourt '
Public Function GetJudgespkJudgesJudgeNamefkCourt(ByVal ClientKey As Integer, ByVal fkCourt As Integer) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim sqlCommand As String = "USP_DISPLAYJUDGESPKJUDGEJUDGENAMEFKCOURT"
Dim dbCommand As DbCommand = db.GetStoredProcCommand(sqlCommand)
db.AddInParameter(dbCommand,"ClientKey", DbType.Int32, ClientKey)
db.AddInParameter(dbCommand,"fkCourt", DbType.Int32, fkCourt)
Return db.ExecuteDataSet(dbCommand)
End Function
Partial Class CaseEntry
Inherits System.Web.UI.Page
Private JudgeDataTable As System.Data.DataTable
Private Sub S_GetJudges(ByVal courtID As Integer)
' Load the list of judges
JudgeDataTable = New System.Data.DataTable
Dim JudgeSet As New DataSet
Dim dv As System.Data.DataView
Dim DAl As New DataAccessLayer
Dim pfkCourt As Integer = CourtDDL.SelectedValue
If ClientKey > 0 And pfkCourt > 0 Then
JudgeSet = DAl.GetJudgespkJudgesJudgeNamefkCourt(ClientKey, pfkCourt)
JudgeDataTable = JudgeSet.Tables(0)
Dim dr As System.Data.DataRow
dr = JudgeDataTable.NewRow()
dr("pkJudge") = "0"
dr("Judge Name") = "(Select a Judge)"
JudgeDataTable.Rows.Add(dr)
JudgeDDL.SelectedValue = 0
JudgeDDL.DataSource = JudgeDataTable.DefaultView
dv = JudgeDataTable.DefaultView
dv.Sort = "pkJudge ASC"
JudgeDDL.DataBind()
End If
End Sub
'Retreives fields pkJudge and [Judge Name] from the table Judges where field fkCourt is equal to fkCourt
Public Function GetJudgespkJudgesJudgeNamefkCourt(ByVal ClientKey As Integer, ByVal fkCourt As Integer) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim sqlCommand As String = "USP_DISPLAYJUDGESPKJUDGEJUDGENAMEFKCOURT"
Dim dbCommand As DbCommand = db.GetStoredProcCommand(sqlCommand)
db.AddInParameter(dbCommand, "ClientKey", DbType.Int32, ClientKey)
db.AddInParameter(dbCommand, "fkCourt", DbType.Int32, fkCourt)
Return db.ExecuteDataSet(dbCommand)
End Function
What happens if you break after the getdataset stuff and look at the datatable? Is the column there? Otherwise, maybe try to access it via column index.

Resources