DataTable dt = new DataTable();
string str;
string[] s = Array.ConvertAll<DataRow, string>(dt.Select(), delegate(DataRow row)
{
return (string)row[""];
});
str = String.Join(",", s);
Are you looking for something like following:
Dim dt As DataTable = New DataTable()
Dim str As String
Dim s As String() = Array.ConvertAll(Of DataRow, String)(dt.Select(), Function(row As DataRow) DirectCast(row(""), String))
str = String.Join(",", s)
In case of VB 8.0 (.Net 2.0), it does not support anonymous methods. To workaround that, use following code:
Dim dt As DataTable = New DataTable()
Dim str As String
Dim s As String() = Array.ConvertAll(Of DataRow, String)(dt.Select(), AddressOf ConvertRowToString)
str = String.Join(",", s)
ConvertRowToString function:
Function ConvertRowToString(ByVal row As DataRow) As String
Return DirectCast(row(""), String)
End Function
Related
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
I have an array like below
(0) = "apple"
(1) = "orange"
How can I add some string to all item in array? like apple become 'apple', orange become 'orange'
Edited
Private Sub test()
Dim txtReader As TextReader = New StreamReader("data.csv")
Dim parser = New CsvParser(txtReader)
Dim str As String = ""
'Ignore first line
parser.Read()
While True
Dim row = parser.Read()
If row Is Nothing Then
Exit While
End If
str &= $"({String.Join(",", row)}),"
End While
str_record = str.TrimEnd(",")
End Sub
Private Sub Model_Insert()
Dim data As String = ""
Dim query As String = "INSERT INTO main_item(item_code,item_name,item_desc,item_unitprice,item_barcode,dept_id,cat_id,gst_id,set_item,active)" &
"VALUES " & str_record & ""
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Sub
Im trying to create a string and use it in INSERT INTO
Use a For-loop:
Dim array = {"apple", "orange"}
For i As Int32 = 0 To array.Length - 1
array(i) = $"'{array(i)}'"
Next
If you can't use string interpolation yet, use String.Format (or string concatenation):
For i As Int32 = 0 To array.Length - 1
array(i) = String.Format("'{0}'", array(i))
Next
If you don't mind recreating the array, you could use Linq Select:
Dim testarray As String() = New String() {"orange", "apple"}
testarray = testarray.Select(Function(x) String.Format("'{0}'", x)).ToArray()
I'm trying to get three string values from a query, but this call to the function:
argVals = GetArgValsForCompanyName(coName)
...fails to compile with the err msg, "Value of type 'String' cannot be converted to '1-dimensional array of String'."
Nor does this line at the end of that function compile:
Return args
...which fails with, "Value of type '1-dimensional array of String' cannot be converted to 'String'."
I am declaring argVals like so, as an array of string of three vals:
Dim argVals(2) As String
...and the function like so:
Protected Function GetArgValsForCompanyName(coName As String) As String
For more context, here is the pertinent code in its (I think) entirety:
Private Sub Button1_Click( sender As Object, e As EventArgs) Handles Button1.Click
Dim connStr As String = "SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=vonnegut;PWD=ryecatcher"
Dim upd8DML As String = "UPDATE CustomerCategoryLog SET Category = 'Exploding' WHERE Unit = #Unit And MemberNo = #MemberNo AND Custno = #CustNo"
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curIndexVal As String
For Each cntrl As Control In Me.Controls
If TypeOf cntrl Is CheckBox Then
If DirectCast(cntrl, CheckBox).Checked = True Then
curIndexVal = CStr(DirectCast(cntrl, CheckBox).Tag)
coName = GetLabelTextForID(curIndexVal)
argVals = GetArgValsForCompanyName(coName)
_Unit = argVals(0)
_MemberNo = argVals(1)
_CustNo = argVals(2)
Using conn As New SqlConnection(connStr), _
cmd As New SqlCommand(upd8DML, conn)
cmd.Parameters.Add("#Unit", SqlDbType.VarChar, 50).Value = _Unit
cmd.Parameters.Add("#MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
cmd.Parameters.Add("#CustNo", SqlDbType.VarChar, 50).Value = _CustNo
conn.Open
cmd.ExecuteScalar()
End Using
End If
End If
Next
End Sub
Protected Function GetArgValsForCompanyName(coName As String) As String
Dim args(2) As String
Dim sqlConnection1 As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=salinger;PWD=dresdenoflions")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
cmd.Connection = sqlConnection1
sqlConnection1.Open()
sqlConnection1.Open()
reader = cmd.ExecuteReader()
If reader.HasRows Then
args(0) = reader.Item(0).ToString()
args(1) = reader.Item(1).ToString()
args(2) = reader.Item(2).ToString()
End If
reader.Close()
sqlConnection1.Close()
Return args
End Function
What am I getting wrong here? How can I pass back an array of string from a function, and then store those vals in three vars (dims)?
NOTE: If I try to declare the function like so:
Protected Function GetArgValsForCompanyName(coName As String) As String(2)
...I get, "Array bounds cannot appear in type specifiers"
Your problem seems to be that you have the function signiture like so
Protected Function GetArgValsForCompanyName(coName As String) As String
When it should be like this
Protected Function GetArgValsForCompanyName(coName As String) As String()
The () at the end of the return type states that it will be a string array, and not just a string.
I have this code written in Visual basic:
Dim directory As String = Application.StartupPath()
Dim dirinfo As New DirectoryInfo(directory)
Dim filesnatt As String() = dirinfo.GetFiles("*.nat")
Dim filenatt As String
For Each filenatt In filesnatt
Dim filenat As String = Str(filenatt)
Using re As StreamReader = New StreamReader(filenat)
Dim val As String = re.ReadLine()
If val.Contains(TextBox2.Text) Then
Dim a1 As String = filenat
a1 = a1.Remove(".nat")
ComboBox2.Items.Add(a1)
End If
End Using
Next
But I get this error: Value of '1 - dimensional array of System.IO.FileInfo' cannot be converted to '1 - dimensional array of String' because 'System.IO.FileInfo' is not derived from 'String'.
How to fix that?
thats because GetFiles returns FileInfo instead of String change
Dim filesnatt as String() to Dim filesnatt as FileInfo()
and
Dim filenatt as String to Dim filenatt as FileInfo
and in the For Each loop use
Dim filenat as String = filenatt.FullName
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