converting dataset.Compute("Sum(TARGET_AREA)", "") to .toString("N") - vb.net

I am trying to convert my computed database columns in my datagrid. I was able to compute the columns and wanted to fix the format of the results.
Label18.Text = dataset.Compute("Sum(TARGET_AREA)", "") & " (ha)"
An example of my output is 100000.00 (ha)
What I wanted for my output is to look like this 100,000.00 (ha)
I tried using .toString("N") but no luck.
my column type is Decimal and the others were Double.
Any idea on how to fix it?

You could use String.Format method.
Example
value = 1234.567890
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture))
Source: MSDN Custom Numeric Format Strings.
Here is an example using a DataTable - Note that you may want to check the sum if the column allows nulls. Also, the sum here is invoked over the datatable object not the dataset (as in your question) - This code has been automatically translated from C# - I assume it syntactically OK.
Dim dataset As New DataSet("ds1")
Dim dt As New DataTable("dt")
Dim dc As DataColumn = dt.Columns.Add("TARGET_AREA", GetType(System.Decimal))
Dim dr As DataRow = dt.Rows.Add()
dr("TARGET_AREA") = 100000.0
Dim finalResult As String = ""
Dim value As Decimal
If dt.Rows.Count > 0 Then
Dim result_obj As Object = dt.Compute("Sum(TARGET_AREA)", "")
If result_obj Is System.DBNull.Value Then
value = 0
Else
value = Convert.ToDecimal(result_obj)
End If
finalResult = String.Format(value.ToString("0,0.00", System.Globalization.CultureInfo.InvariantCulture)) & " (ha)"
Console.WriteLine(finalResult)
End If
Console.Read()
Return

Related

How to format textfiles values retrieved from a directory and displayed in datagridview in vb.net

The problem now is how would I be able to format the values being displayed in datagridview from textfiles.
I have retrieved values from looping through textfiles removed the first two strings. Now I want to add separators or change the format of the displayed value like, for example:
textfile lines: result:
01Sample - line1
022 - line2
0306212019 - line3 06/21/2019
041234567890 - line4 12,345,678.90
I have already tried this one changing the defaultcellstyle but since the values are from textfiles in a directory its not affecting the output
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
Private Sub ReadTextFiles()
Dim dt As New DataTable
dt.Columns.Add("Date")
dt.Columns.Add("Gross Sales")
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
lstLines.AddRange(File.ReadAllLines(fileentries))
Next
Dim i As Integer
Dim OuterLoopIterations As Integer = CInt(lstLines.Count / 22)
For iterations = 0 To OuterLoopIterations - 1
Dim row = dt.NewRow
For col = 0 To 21
row(col) = lstLines(i).Remove(0, 2) 'i have removed the first 2 characters of each string
i += 1
Next
dt.Rows.Add(row(2), row(5), row(12), row(13), row(14), row(15), row(7), row(8), row(11))
Next
DataGridView1.DataSource = dt
'the code i tried applying
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
this is my expected result
Current datagrid view:
the result should be for date column: 06/07/2019
for the gross : 48,990.14
Edit:
I tried this one
Dim B As Double
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
B = CDbl(Val(fileentries))
lstLines.AddRange(File.ReadAllLines(B))
Next
If you want to format something as a number then it has to be a number. That means that, for example, if you read the text "1234.5" from the file and you want to display it as 1,234.50 in your grid then you have to convert the String you read to a Double or Decimal. If you do that then the numeric format specifier you're using in the grid column will work.

Editing Datable before binding to listview in vb.net

hi this is my code to get datable from query but i need to check for some values like if there is 0 in any column then replace it with N.A.
Dim op As New cad
Dim dt As DataTable = op.Fetchbooks().Tables(0)
Dim sb As New StringBuilder()
Dim rp As System.Data.DataRow
If dt.Rows.Count > 0 Then
ListView1.DataSource = dt
ListView1.DataBind()
DropDownList1.DataSource = dt
DropDownList1.DataTextField = "Description"
DropDownList1.DataValueField = "Description"
DropDownList1.DataBind()
End if
so is there any way to check some values and edit in datable before binding ???
First, if possible i would modify your sql-query in Fetchbooks instead to replace 0 with N.A.. I assume you are querying the database.
However, if you want to do it in memory:
For Each row As DataRow In dt.Rows
For Each col As DataColumn In dt.Columns
If row.IsNull(col) OrElse row(col).ToString = "0" Then
row(col) = "N.A."
End If
Next
Next
Sure: you can iterate through the table, making whatever value replacements are appropriate (assuming that your replacement values are type-compatible with what came from the query).
Something like:
For Each row as DataRow in dt.Rows
if row("columnname") = "left" then
row("columnname") = "right"
Next
Then bind it to the grid, and you should see your updated values.
Once you have the DataTable object you can manipulate it as you need:
For Each rp In dt.Select("COLUMN_A = '0'")
rp("COLUMN_A") = "N.A."
Next
Note that this assumes that COLUMN_A is defined as a string type, not a numeric.
The challenge will be if you intend on saving this data back to it's source and you don't want the original 0 value to be saved instead of N.A.. You could add dt.AcceptChanges immediately after the above loop so that it will appear as the Fetchbooks query had these values all along.

Adding two column values to listbox in vb.net

I have a table named users which has the following columns in it
User_id,user_name,user_pwd,First_Name,Middle_Name,Last_Name and user_type.
I have dataset named dst and created a table called user in the dataset. Now I want to populate listbox with user_Name, First_Name, Last_name of each and every row in the table user.
I am able to add one column value at a time but not getting how to add multiple column values of each row to listbox
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(row("User_Name"))
Next
Above code works perfectly but I also want to add First_name as well as last_name to the list box at the same time.
Use same approach as you have, but put all values you want in one string.
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
Dim sItemTemp as String
sItemTemp = String.Format("{0},{1},{2}", row("User_Name"), row("First_Name"), row("Last_Name"))
lstUsers.Items.Add(sItemTemp)
Next
String.Format() function will call .ToString() on all parameters.
In this case if row(ColumnName) is NULL value then .ToString() return just empty string
You have 2 choices:
Using the ListBox:
To use the ListBox, set the font to one that is fixed width like courier new (so that the columns line up), and add the items like this:
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(RPAD(row("User_Name"),16) & RPAD(row("First_Name"),16) & RPAD(row("Last_Name"),16))
Next
The RPAD function is defined like this:
Function RPAD(a As Object, LENGTH As Object) As String
Dim X As Object
X = Len(a)
If (X >= LENGTH) Then
RPAD = a : Exit Function
End If
RPAD = a & Space(LENGTH - X)
End Function
Adjust the LENGTH argument as desired in your case. Add one more for at least one space. This solution is less than ideal because you have to hard-code the column widths.
Use a DataGridView control instead of a ListBox. This is really the best option, and if you need, you can even have it behave like a ListBox by setting the option to select the full row and setting CellBorderStyle to SingleHorizontal. Define the columns in the designer, but no need to set the widths - the columns can auto-size, and I set that option in the code below. if you still prefer to set the widths, comment out the AutoSizeColumnsMode line.
The code to set up the grid and add the rows goes like this:
g.Rows.Clear() ' some of the below options are also cleared, so we set them again
g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells
g.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal
g.SelectionMode = DataGridViewSelectionMode.FullRowSelect
g.AllowUserToAddRows = False
g.AllowUserToDeleteRows = False
g.AllowUserToOrderColumns = True
For Each row As DataRow In dt.Rows
g.Rows.Add(row("User_Name"), row("First_Name"), row("Last_Name"))
Next
You might solved your problem by now but other users like me might have issue with it.
Above answers given worked for me even but I found a same answer in a simple way according to what I want..
cmd = New SqlCommand("select User_Name, First_Name, Last_Name from User")
Dim dr As SqlDataReader = cmd.ExecuteReader(YourConnectionString)
If dr.HasRows Then
Do While dr.Read
lst.Items.Add(dr.Item(0).ToString & " " & dr.Item(1).ToString & " " & dr.Item(2).ToString)
Loop
End If
This worked for me, maybe wrong way but I found it simple :)
May I suggest you use a ListView control instead of Listbox?
If you make the switch, here's a sample subroutine you could use to fill it up with the data you said you want. Adapt it the way you like; there's much room for improvement but you get the general idea:
Public Sub FillUserListView(lstUsers As ListView, Dst As DataSet)
Dim columnsWanted As List(Of String) = New List(Of String)({"User_Name", "First_Name", "Last_Name"})
Dim dt As DataTable = Dst.Tables("user")
Dim columns As Integer = 0
Dim totalColumns = 0
Dim rows As Integer = dt.Rows.Count
'Set the column titles
For Each column As DataColumn In dt.Columns
If columnsWanted.Contains(column.ColumnName) Then
lstUsers.Columns.Add(column.ColumnName)
columns = columns + 1
End If
totalColumns = totalColumns + 1
Next
Dim rowObjects(columns - 1) As ListViewItem
Dim actualColumn As Integer = 0
'Load up the rows of actual data into the ListView
For row = 0 To rows - 1
For column = 0 To totalColumns - 1
If columnsWanted.Contains(dt.Columns(column).ColumnName) Then
If actualColumn = 0 Then
rowObjects(row) = New ListViewItem()
rowObjects(row).SubItems(actualColumn).Text = dt.Rows(row).Item(actualColumn)
Else
rowObjects(row).SubItems.Add(dt.Rows(row).Item(actualColumn))
End If
lstUsers.Columns.Item(actualColumn).Width = -2 'Set auto-width
actualColumn = actualColumn + 1
End If
Next
lstUsers.Items.Add(rowObjects(row))
Next
lstUsers.View = View.Details 'Causes each item to appear on a separate line arranged in columns
End Sub

VB.net incremented number concatenate with texbox value

I'm learning vb.net. I'm trying to create an incremental number that starts at 00000 and concatenate that number with a value from a textbox (eg. JH00001), then insert it into the database.
Please can someone kindly help me with this as I'm totaly new to vb.net.
Thank you all for your assistance in advance. And I'm sorry for my bad English.
Dim number as Integer = 1
Dim text as String = textbox1.text &= number.toString().padLeft(5, "0"c)
Use D5 precision specifier to indicate that the number should be at least 5 digits including leading zeros:
Dim valueFromTextBox As String = "JH"
Dim value As String = ""
For i = 0 To 99
value = valueFromTextBox & i.ToString("D5")
'Insert value to database
Next
Check MSDN for more formatting methods
A for loop should be what you need:
Something like:
Dim text As String = textbox1.text
Dim DBtext As String
For value As Integer = 0 To 5
DBtext = text & value.ToString()
'Insert anything else you need to do. Such as insert into DB.
Next
Just replace the 5 with however many times you need it to run.
I personally prefer using String.Format ...
For i = 0 to 1e6-1
Dim FormattedString = String.Format("{0}{1:00000}", Textbox1.Text, i)
Next

String conversion for SQL select statement

Using a SELECT statement I query a database and get back a result in the format: name1,name2,name3
Depending on the database entry this result could have any number of names: name1,name2...name(n)
I would like to use this data to query another database like so:
SELECT Name, SerialNo, Model FROM InstrumentTable where ID=1 and InstName IN name1,name2,name3
In order to do this I need to convert name1,name2,name3 to ('name1','name2','name3')
I have tried splitting the String into an array of Strings
Dim ref1s As String = cmdf1.ExecuteScalar()
Dim fields() As String = Nothing
fields = ref1s.Split(",")
and then concatenating them in an array
For i As Integer = 0 To fields.Count - 1
MsgBox(String.Concat("'", fields(i), "'"))
Next
but I haven't been able to figure out how to do it yet.
Adding the brackets at the start and end of the string shouldn't be a problem just adding the quotes to each name and separating them with a comma is the issue.
Can anyone help me with this?
You got a bit previous
For i As Integer = 0 To fields.Count - 1
fields[i] = String.Concat("'",fields[i],"'")
Next
Then
strValue = fields.Join(',')
user557425,
Something like this might point you in the right direction:
Dim lst As List(Of String)
For i As Integer = 0 to fields.Count - 1
if i = fields.Count - 1 Then
lst.Add(fields(i) & "'")
Else
lst.Add(fields(i) & "','")
End if
Next
Dim sqlSB As StringBuilder
sqlSB.Append("SELECT * FROM TABLE WHERE BLAH IN(")
For each s As String in lst
sqlSB.Append(s)
Next
'use the stringbuilder as command text in a SqlCommand...