Calculate values in strings - vb.net

I need to calculate labels values and I want the result to be formatted with 2 decimals digits.
The code I'm using is:
Dim culture = CultureInfo.CreateSpecificCulture("us-US")
Dim diff = CDec(CStr((Decimal.Parse(Label13.Text, culture) * Decimal.Parse(Label16.Text, culture)))) - Decimal.Parse(Label15.Text, culture)
If diff > 0 Then
Label20.ForeColor = Color.Green
Label20.Text = CStr(diff) '((CDbl(Label13.Text) * CDbl(Label16.Text)) - CDbl(Label15.Text)).ToString("n2")
Else
Label20.ForeColor = Color.Red
Label20.Text = CStr(diff) '((CDbl(Label13.Text) * CDbl(Label16.Text) - CDbl(Label15.Text))).ToString("n2")
End If
The input is:
label13.text= 0,600
label15.text=11,157
label16.text= 18,110
label20.text should be= -0,29
instead, the output im getting is
label20.text= - 4462,800
Where it comes from?
It s quite weird cause with this input it's working
label13.text= 1000
label15.text=107,4
label16.text= 0.10296
label20.text= -4.44
Thanks
Edit1:
Imports System.Globalization
Imports System.Net
Imports Newtonsoft.Json
Public Class Form1
'DICHIARO I WEBCLIENT
Private ReadOnly wcBTT As New WebClient()
Private ReadOnly wcUNI As New WebClient()
Private ReadOnly wcVET As New WebClient()
Private ReadOnly wcCAKE As New WebClient()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label4.Text = My.Settings.BTTQ
Label5.Text = My.Settings.BTTP
Label6.Text = My.Settings.BTTINV
Label7.Text = My.Settings.UNIQ
Label8.Text = My.Settings.UNIP
Label9.Text = My.Settings.UNIINV
Label10.Text = My.Settings.VETQ
Label11.Text = My.Settings.VETP
Label12.Text = My.Settings.VETINV
Label13.Text = My.Settings.CAKEQ
Label14.Text = My.Settings.CAKEP
Label15.Text = My.Settings.CAKEINV
End Sub
Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'FERMO IL TIMER ALTRIMENTI OPERAZIONI I/O SIMULTANEE
Timer1.Stop()
Dim downloadTasks As New List(Of Task(Of String))
' SCARICO IL CONTENUTO DELLE API E LO DICHIARO "DIM BTC AS TASK(OF STRING)
Dim btt = wcBTT.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=BTTBUSD")
Dim uni = wcUNI.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=UNIBUSD")
Dim vet = wcVET.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=VETBUSD")
Dim cake = wcCAKE.DownloadStringTaskAsync("https://api.binance.com/api/v1/ticker/24hr?symbol=CAKEBUSD")
downloadTasks.Add(btt)
downloadTasks.Add(uni)
downloadTasks.Add(vet)
downloadTasks.Add(cake)
Await Task.WhenAll(downloadTasks)
'DESERIALIZZO LE API NORMALI
Dim settings = New JsonSerializerSettings With {.Culture = CultureInfo.InvariantCulture}
Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(btt.Result, settings)
Dim d1 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(uni.Result, settings)
Dim d2 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(vet.Result, settings)
Dim d3 = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(cake.Result, settings)
Dim PREZZOBTT As Decimal = Decimal.Parse(CStr(d("lastPrice")), CultureInfo.InvariantCulture)
Dim PREZZOUNI As Decimal = Decimal.Parse(CStr(d1("lastPrice")), CultureInfo.InvariantCulture)
Dim PREZZOVET As Decimal = Decimal.Parse(CStr(d2("lastPrice")), CultureInfo.InvariantCulture)
Dim PREZZOCAKE As Decimal = Decimal.Parse(CStr(d3("lastPrice")), CultureInfo.InvariantCulture)
'CONNETTO LE API NORMALI ALLE LABEL
Label1.Text = PREZZOBTT.ToString("n7")
Label2.Text = PREZZOUNI.ToString("n3")
Label3.Text = PREZZOVET.ToString("n5")
Label16.Text = PREZZOCAKE.ToString("n3")
'GAIN/LOSS
'BTT
Dim diffbtt = (PREZZOBTT * Decimal.Parse(Label4.Text) - Decimal.Parse(Label6.Text)).ToString("n2")
If CInt(diffbtt) > 0 Then
Label17.ForeColor = Color.Green
Label17.Text = CStr(diffbtt)
Else
Label17.ForeColor = Color.Red
Label17.Text = CStr(diffbtt) '
End If
''UNI
Dim diffuni = (Decimal.Parse(Label7.Text) * PREZZOUNI - Decimal.Parse(Label9.Text)).ToString("n2")
If CInt(diffuni) > 0 Then
Label18.ForeColor = Color.Green
Label18.Text = CStr(diffuni)
Else
Label18.ForeColor = Color.Red
Label18.Text = CStr(diffuni) '
End If
''VET
Dim diffvet = (PREZZOVET * Decimal.Parse(Label10.Text) - Decimal.Parse(Label12.Text)).ToString("n2")
If CInt(diffvet) > 0 Then
Label19.ForeColor = Color.Green
Label19.Text = CStr(diffvet)
Else
Label19.ForeColor = Color.Red
Label19.Text = CStr(diffvet) '
End If
''CAKE
Dim diffcake = (Decimal.Parse(Label13.Text) * PREZZOCAKE - Decimal.Parse(Label15.Text)).ToString("n2")
If CInt(diffcake) > 0 Then
Label20.ForeColor = Color.Green
Label20.Text = CStr(diffcake)
Else
Label20.ForeColor = Color.Red
Label20.Text = CStr(diffcake)
End If
Timer1.Start()
End Sub

I would drop Decimal type, use Double, and use the string Format command for ensuring 2 digit precision in the results of the delta (diff). The parsing can take a string argument, so you don't need to convert to CDbl() first -- besides, how can you convert to double if you are trying to determine if what's being tested is double? The return from Format is a string result, so it doesn't need CStr(), .ToString, etc.
Dim lab3, lab5, lab6, diff As Double
Dim parseresult As Object
If Double.TryParse(Label3.Text, parseresult) = True Then
lab3 = CDbl(Label3.Text)
End If
If Double.TryParse(Label5.Text, parseresult) = True Then
lab5 = CDbl(Label5.Text)
End If
If Double.TryParse(Label6.Text, parseresult) = True Then
lab6 = CDbl(Label6.Text)
End If
diff = lab3 * lab6 - lab5
If diff > 0 Then
Label20.ForeColor = Color.Green
Label20.Text = Format(diff, "0.00"))
Else
Label20.ForeColor = Color.Red
Label20.Text = Format(diff, "0.00")
End If
If you need to kill the currency type, i.e., if "$" is in the label strings, then replace it with
lab3str = Label3.Text.Replace("$","")
and then parse lab3str.

Related

VB report error System.InvalidCastException: Operator '+' is not defined for type 'Double' and type 'DBNull'

Error: error line 369
Line 367: For intTeller = 0 To tblData.Rows.Count - 1
Line 368: With tblData.Rows(intTeller)
Line 369: .Item("Projected") = .Item("Sales") + .Item("ShippedNotInvoiced") + .Item("OpenOrdersCurrentPeriod")
Line 370: End With
Line 371: Next
Code
Imports System.Data.SqlClient
Partial Class Sales
Inherits System.Web.UI.Page
Dim tblData As New Data.DataTable
Private Sub DataGridToExcel(ByRef grdExport As GridView, ByRef pResponse As Web.HttpResponse, ByVal pFileName As String)
Try
Dim intTeller As Integer = 0
Dim strTemp As String
pResponse.Clear()
pResponse.AddHeader("content-disposition", "attachment;filename=" & pFileName)
pResponse.Buffer = True
pResponse.ContentType = "application/vnd.ms-excel"
pResponse.Charset = ""
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)
grdExport.RenderControl(htmlWrite)
strTemp = stringWrite.ToString
strTemp.Replace(",", "")
strTemp.Replace(".", "")
pResponse.Write(strTemp)
pResponse.End()
Catch ex As Exception
'Me.lblError.Text = ex.Message
End Try
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Private Sub sExportGrid()
DataGridToExcel(Me.grdSalesLines, Response, "Sales " & Format(Now, "yyyyMM") & ".xls")
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
sCreateTable()
sFillPeriods()
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
End If
End Sub
Private Sub sFillPeriods()
Dim conMain As New SqlConnection(sGetConnectionString)
Dim comMain As SqlCommand
Dim drMain As SqlDataReader
Dim strSQL As String = "SELECT DISTINCT Period FROM [SR_SalesOverviewCompany] Order by Period DESC"
conMain.Open()
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
Me.cmbPeriods.Items.Clear()
Me.cmbPeriods.Items.Add("Current Period")
Me.cmbPeriods.Items.Add("Year To Date")
If drMain.HasRows Then
While drMain.Read
If Not IsDBNull(drMain.Item("Period")) Then
Me.cmbPeriods.Items.Add(drMain.Item("Period"))
End If
End While
End If
End Sub
Private Function sGetConnectionString() As String
Dim conString = ConfigurationManager.ConnectionStrings("STOKVIS LIVEConnectionString")
Dim strConnString As String = conString.ConnectionString
Return strConnString
End Function
Protected Sub grdSalesLines_DataBound(sender As Object, e As System.EventArgs) Handles grdSalesLines.DataBound
If Me.cmbPeriods.SelectedItem.Text <> "Current Period" Then
grdSalesLines.Columns(3).Visible = False
grdSalesLines.Columns(4).Visible = False
grdSalesLines.Columns(5).Visible = False
grdSalesLines.Columns(7).Visible = False
Else
grdSalesLines.Columns(3).Visible = True
grdSalesLines.Columns(4).Visible = True
grdSalesLines.Columns(5).Visible = True
grdSalesLines.Columns(7).Visible = True
End If
End Sub
Protected Sub grdSalesLines_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdSalesLines.RowCommand
Dim intRow As Integer = CInt(e.CommandArgument)
Response.Redirect("SalesDetails.aspx?p=" & Me.cmbPeriods.SelectedItem.Text & "&s=" & grdSalesLines.Rows(intRow).Cells(1).Text)
End Sub
Protected Sub grdSalesLines_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdSalesLines.RowDataBound
Dim intCounter As Integer
If e.Row.Cells(1).Text = "Total" Then
For intCounter = 0 To e.Row.Cells.Count - 1
With e.Row.Cells(intCounter)
.ForeColor = Drawing.Color.White
.BackColor = Drawing.Color.DarkBlue
.Font.Bold = True
End With
Next
End If
End Sub
Private Sub sCreateTable()
tblData.Columns.Clear()
tblData.Columns.Add(New Data.DataColumn("Code", System.Type.GetType("System.String")))
tblData.Columns.Add(New Data.DataColumn("Salesperson", System.Type.GetType("System.String")))
tblData.Columns.Add(New Data.DataColumn("OpenOrders", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("OpenOrdersCurrentPeriod", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("ShippedNotInvoiced", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Sales", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Projected", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("Budget", System.Type.GetType("System.Double")))
tblData.Columns.Add(New Data.DataColumn("PreviousYear", System.Type.GetType("System.Double")))
End Sub
Protected Sub btnRefresh_Click(sender As Object, e As System.EventArgs) Handles btnRefresh.Click
If Me.cmbPeriods.SelectedItem.Text = "Current Period" Then
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
Else
sRefreshData(Me.cmbPeriods.SelectedItem.Text, "")
End If
End Sub
Protected Sub btnExcel_Click(sender As Object, e As System.EventArgs) Handles btnExport.Click
sExportGrid()
End Sub
Protected Sub cmbPeriods_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cmbPeriods.SelectedIndexChanged
sCreateTable()
If Me.cmbPeriods.SelectedItem.Text = "Current Period" Then
sRefreshData(Format(Now, "yyyyMM"), Format(DateAdd(DateInterval.Year, -1, Now), "yyyyMM"))
Else
sRefreshData(Me.cmbPeriods.SelectedItem.Text, "")
End If
End Sub
Private Sub sRefreshData(pPeriod As String, pPreviousYearPeriod As String)
Dim conMain As New SqlConnection(sGetConnectionString)
Dim comMain As SqlCommand
Dim drMain As SqlDataReader
Dim dtRow As Data.DataRow
Dim strSQL As String
Dim intTeller As Integer
Dim blnYearToDate As Boolean = False
sCreateTable()
If pPeriod = "Year To Date" Then
pPeriod = ""
blnYearToDate = True
End If
strSQL = "SELECT code, Name from SR_SalesPerson"
conMain.Open()
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
dtRow = tblData.NewRow()
dtRow.Item("Code") = drMain.Item("Code")
dtRow.Item("SalesPerson") = drMain.Item("Name")
dtRow.Item("OpenOrders") = 0
dtRow.Item("OpenOrdersCurrentPeriod") = 0
dtRow.Item("ShippedNotInvoiced") = 0
dtRow.Item("Sales") = 0
dtRow.Item("Projected") = 0
dtRow.Item("Budget") = 0
dtRow.Item("PreviousYear") = 0
tblData.Rows.Add(dtRow)
End While
dtRow = tblData.NewRow()
dtRow.Item("Code") = "Total"
dtRow.Item("SalesPerson") = ""
dtRow.Item("OpenOrders") = 0
dtRow.Item("OpenOrdersCurrentPeriod") = 0
dtRow.Item("ShippedNotInvoiced") = 0
dtRow.Item("Sales") = 0
dtRow.Item("Projected") = 0
dtRow.Item("Budget") = 0
dtRow.Item("PreviousYear") = 0
tblData.Rows.Add(dtRow)
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersShippedNotInvoiced"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("ShippedNotInvoiced") = drMain.Item("AmountRest")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersPerSalesperson"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("OpenOrders") = drMain.Item("OpenOrders")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_SalesOpenOrdersPerSalesPersonPerPeriod WHERE Period='" & pPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("SalesPerson Code") Then
tblData.Rows(intTeller).Item("OpenOrdersCurrentPeriod") = drMain.Item("AmountRest")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_BudgetPerSalesPersonPerPeriod WHERE strPeriod='" & pPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("strCode") Then
tblData.Rows(intTeller).Item("Budget") = drMain.Item("dblSales")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
strSQL = "SELECT * FROM SR_HistSalesPerSalesPersonPerPeriod WHERE strPeriod='" & pPreviousYearPeriod & "'"
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("strCode") Then
tblData.Rows(intTeller).Item("PreviousYear") = drMain.Item("dblSales")
End If
Next
End While
End If
drMain.Close()
comMain.Dispose()
If blnYearToDate Then
strSQL = "SELECT Salesperson, SUM(Sales) AS Sales, SUM([Cost of Sales]) AS [Cost of Sales], SUM(Margin) AS Margin, SUM(Margin) / SUM(Sales) AS SalesPercent, Code " & _
"FROM dbo.SR_SalesPerSalesperson " & _
"WHERE (Period LIKE '" & Now.Year & "%') " & _
"GROUP BY Salesperson, Code"
Else
strSQL = "SELECT * FROM SR_SalesPerSalesperson WHERE Period='" & pPeriod & "'"
End If
comMain = New SqlCommand(strSQL, conMain)
drMain = comMain.ExecuteReader
If drMain.HasRows Then
While drMain.Read
For intTeller = 0 To tblData.Rows.Count - 1
If tblData.Rows(intTeller).Item("Code") = drMain.Item("Code") Then
tblData.Rows(intTeller).Item("Sales") = drMain.Item("Sales")
End If
Next
End While
End If
For intTeller = 0 To tblData.Rows.Count - 1
With tblData.Rows(intTeller)
.Item("Projected") = .Item("Sales") + .Item("ShippedNotInvoiced") + .Item("OpenOrdersCurrentPeriod")
End With
Next
Dim intLastRow As Integer = tblData.Rows.Count - 1
For intTeller = 0 To tblData.Rows.Count - 2
With tblData.Rows(intTeller)
tblData.Rows(intLastRow).Item("Sales") += fCheckValue(.Item("Sales"))
tblData.Rows(intLastRow).Item("OpenOrders") += fCheckValue(.Item("OpenOrders"))
tblData.Rows(intLastRow).Item("OpenOrdersCurrentPeriod") += fCheckValue(.Item("OpenOrdersCurrentPeriod"))
tblData.Rows(intLastRow).Item("ShippedNotInvoiced") += fCheckValue(.Item("ShippedNotInvoiced"))
tblData.Rows(intLastRow).Item("Projected") += fCheckValue(.Item("Projected"))
tblData.Rows(intLastRow).Item("Budget") += fCheckValue(.Item("Budget"))
tblData.Rows(intLastRow).Item("PreviousYear") += fCheckValue(.Item("PreviousYear"))
End With
Next
Me.grdSalesLines.DataSource = tblData
Me.grdSalesLines.DataBind()
Try
drMain.Close()
comMain.Dispose()
conMain.Close()
Catch ex As Exception
End Try
End Sub
Private Function fCheckValue(pField As Object) As Double
Dim dblValue As Double = 0
If IsDBNull(pField) Then
dblValue = 0
Else
dblValue = CDbl(pField)
End If
Return dblValue
End Function
End Class
First, it might be useful to have a helper function such as the following:
Private Function GetNullableValue(Of T)(ByVal dataRow As DataRow, ByVal columnName As String, ByVal defaultIfNull As T) As T
If Not IsDBNull(dataRow.Item(columnName)) Then
Return CType(dataRow.Item(columnName), T)
End If
Return CType(defaultIfNull, T)
End Function
To check for DBNull, you could then modify your code as follows:
For intTeller = 0 To tblData.Rows.Count - 1
Dim row As DataRow = tblData.Rows(intTeller)
With row
.Item("Projected") = GetNullableValue(row, "Sales", 0) + GetNullableValue(row, "ShippedNotInvoiced", 0) + GetNullableValue(row, "OpenOrdersCurrentPeriod", 0)
End With
Next
NOTE: The above should side-step the exception. However, the fact that one of these columns is null may be indicative of another problem - e.g. perhaps there are problems with the query or the data

Operator '+' is not defined for type 'Decimal' and type 'DBNull'

im working to show the data in my datagrid,and show the total of items brought in textbox2,but this error "Operator '+' is not defined for type 'Decimal' and type 'DBNull'." what is the problem? please help me i need to finish this so badly. :(
Private Sub dailySales_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Connect()
DataGridView1.DataSource = dtb
dtb.Columns.Add("Transaction Code")
dtb.Columns.Add("Transaction Date ")
dtb.Columns.Add("Item Code")
dtb.Columns.Add("Item")
dtb.Columns.Add("Description")
dtb.Columns.Add("Quantity")
dtb.Columns.Add("Price")
dtb.Columns.Add("Total")
display()
con.Close()
total()
TextBox1.Text = DataGridView1.RowCount()
Me.DataGridView1.DefaultCellStyle.Font = New Font("Cambria", 10)
Me.DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("Cambria", 12)
Me.DataGridView1.DefaultCellStyle.SelectionBackColor = Color.FromArgb(129, 207, 224)
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
End Sub
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub
Sub display()
con.Connect()
Label6.Text = Date.Now.ToString("dd MMMM yyyy")
Dim da = Label6.Text
Dim sc = " where lower(tns_date) like lower('%" & da & "%') "
Dim sql = "select * from tns " & sc & " order by tns_code desc"
odr = con.Retrieve(sql)
dtb.Clear()
While (odr.Read)
Dim ic = odr.GetOracleValue(0)
Dim itn = odr.GetOracleValue(1)
Dim de = odr.GetOracleValue(2)
Dim ca = odr.GetOracleValue(3)
Dim pr = odr.GetOracleValue(4)
Dim st = odr.GetOracleValue(5)
Dim sst = odr.GetOracleValue(6)
dtb.Rows.Add(ic, itn, de, ca, pr, st, sst)
End While
con.Close()
End Sub
Test like this.
Sub total()
Dim sum As Decimal = 0
For x = 0 To DataGridView1.Rows.Count - 1
If Not isDBNull(DataGridView1.Rows(x).Cells(7).Value) then sum =sum + DataGridView1.Rows(x).Cells(7).Value
Next
TextBox2.Text = sum
End Sub

Hangman vb.net only first letter showing

Basically I generate a random word for example
"Tree" and when I press the T button it changes the label into a T but then when I choose R it doesnt show, can someone else see what i've done wrong?
here is my code
Sub GuessLetter(ByVal LetterGuess As String)
Dim strGuessedSoFar As String = Lbltempword.Text
Dim LengthOfSecretWord As Integer
LengthOfSecretWord = secret.Length - 1
tempWord = ""
Dim letterPosition As Integer
For letterPosition = 0 To LengthOfSecretWord
If secret.Substring(letterPosition, 1) = LetterGuess Then
tempWord = tempWord & LetterGuess
Else
tempWord = tempWord & Lbltempword.Text.Substring(letterPosition, 1)
End If
Next
Lbltempword.Text = tempWord
If Lbltempword.Text = secret Then 'YOU WIN
DisableButtons()
BtnStart.Enabled = True
MsgBox("YOU WIN")
End If
If Lbltempword.Text = strGuessedSoFar Then
NumWrong = NumWrong + 1
End If
DisplayHangman(NumWrong)
End Sub
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
randomword()
MsgBox(secret)
EnableButtons()
BtnStart.Enabled = False
'Load up the temp word label with dashes
Secret_Word = secret
LoadLabelDisplay()
NumWrong = 0
DisplayHangman(NumWrong)
End Sub
Sub LoadLabelDisplay()
Lbltempword.Text = ""
Dim LengthOfSecretWord As Integer
LengthOfSecretWord = secret.Length - 1
Dim LetterPosition As Integer
For LetterPosition = 0 To LengthOfSecretWord
Lbltempword.Text = Lbltempword.Text & "-"
Next
End Sub
I also generate the random words by doing this.
Sub randomword()
Dim RAND(16)
Dim rng As New System.Random()
For i = 0 To 16
RAND(0) = "Tree"
RAND(1) = "Star"
RAND(2) = "Jesus"
RAND(3) = "Present"
RAND(4) = "advent"
RAND(5) = "Calender"
RAND(6) = "Jinglebell"
RAND(7) = "skint"
RAND(8) = "lapland"
RAND(9) = "Santa"
RAND(10) = "raindeer"
RAND(11) = "Cookies"
RAND(12) = "Milk"
RAND(13) = "nothing"
RAND(14) = "play"
RAND(15) = "sack"
Next
secret = RAND(rng.Next(RAND.Count()))
End Sub

Creating a DataGridView Programatically and add clickable cells

Evening
I am struggling to achieve what I have set out todo! In a nutshell I am working with the Google Drive API to create an app in VB.net that allows you to view / download files etc.
Basically I am planning on using a couple of different api's for the different cloud provider s I have. The stage I have got to is that I have my collection of files and there various properties in a list. On load I am checking to see if a google account has been added to my program and if so creating a new tabpage on a tabcontrol, I then create the datagridview and add it to the collection on the new tab page. This works fine and displays all my data as is.
What I am trying to achieve is adding a clickable link to my download column instead of displaying the url. I have been trying to manipulate the code found here C# DataGridViewLinkCell Display after converting it to vb.net. This is basically what I have ended up with:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim dgvlc As New DataGridViewLinkColumn()
dgvlc.ActiveLinkColor = Color.Blue
dgvlc.HeaderText = "Download"
GoogleDriveDGV.Columns.Add(dgvlc)
GoogleDriveDGV.RowHeadersVisible = False
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download File"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
I have two problems that I cant figure out:
1) GoogleDriveDGV is not declared here : For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
2) If I comment out the GoogleDriveDGV_CellContentClick sub and just try to populate the datagridview I get System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.DataGridViewLinkColumn' to type 'customcolumn' here DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(3, DriveFile.DownloadUrl)
Can anyone let me know if what I am trying to achieve is possible and any hints?
Update!!!
I now have this:
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
'Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
' For Each url As KeyValuePair(Of Integer, String) In DirectCast(GoogleDriveDGV.Columns(e.ColumnIndex), customcolumn).urls
' If url.Key = e.RowIndex Then
' Process.Start(url.Value)
' Exit For
' End If
' Next
'End Sub
Which is almost there, I now have the datagridview filled with the items and a download link, just cant work out how to solve issue 1 above :-(
Would you believe it I worked it out :-)
Basically I needed to add a handler.
Full code:
Private Sub CloudManager_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Settings.GoogleClientID <> "" Then
Dim GD As New Properties.GDrive
GD.APIClientID = My.Settings.GoogleClientID
GD.APIClientSecret = My.Settings.GoogleClientSecret
clsDrive.GD = GD
clsDrive.GetSpace()
clsDrive.RefreshFiles()
Dim GoogleDriveTab As New TabPage
GoogleDriveTab.Text = "Google Drive"
tc_CloudManager.TabPages.Add(GoogleDriveTab)
Dim GoogleDriveDGV As New DataGridView
GoogleDriveDGV.Name = "GoogleDriveDGV"
GoogleDriveDGV.Dock = DockStyle.Fill
GoogleDriveDGV.Columns.Add("FileTitle", "File Title")
GoogleDriveDGV.Columns.Add("FileExtension", "File Extension")
GoogleDriveDGV.Columns.Add("FileSize", "File Size")
Dim c As New customcolumn()
GoogleDriveDGV.Columns.Add(c)
AddHandler GoogleDriveDGV.CellContentClick, AddressOf GoogleDriveDGV_CellContentClick
GoogleDriveDGV.RowHeadersVisible = False
For i As Integer = 0 To GoogleDriveDGV.Columns.Count - 1
GoogleDriveDGV.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
Next
Dim trow As Integer = 0
Try
For Each DriveFile In GD.DriveFiles
Dim row As DataGridViewRow = DirectCast(GoogleDriveDGV.Rows(0).Clone, DataGridViewRow)
Dim title As String = DriveFile.Title
If title.Length > 60 Then
title = title.Substring(0, 60)
End If
Dim fs As Integer = DriveFile.FileSize
Dim fsf As String
If fs > 1048576 Then
fsf = Math.Round(fs / 1048576, 2) & " MB"
Else
fsf = fs & " Bytes"
End If
Dim fe As String
If DriveFile.FileExtension = "" Then
fe = "Folder"
Else
fe = DriveFile.FileExtension
End If
row.Cells(0).Value = title
row.Cells(1).Value = fe
row.Cells(2).Value = fsf
row.Cells(3).Value = "Download"
DirectCast(GoogleDriveDGV.Columns(3), customcolumn).urls.Add(trow, DriveFile.DownloadUrl)
GoogleDriveDGV.Rows.Add(row)
trow = trow + 1
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
GoogleDriveTab.Controls.Add(GoogleDriveDGV)
End If
End Sub
Class customcolumn
Inherits System.Windows.Forms.DataGridViewLinkColumn
Public urls As New Dictionary(Of Integer, String)()
End Class
Private Sub GoogleDriveDGV_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
For Each url As KeyValuePair(Of Integer, String) In DirectCast(sender.Columns(e.ColumnIndex), customcolumn).urls
If url.Key = e.RowIndex Then
Process.Start(url.Value)
Exit For
End If
Next
End Sub
End Class

VB.Net Silverlight 5 SQL Entities Searching

Im making a silverlight 5 application and im using RIA WCS services to connect to sql, i can add data,delete data, edit data, and get all data, but the problem is that i need to retrieve a specific record not the whole entity, when i try the following code just nothing happens:
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
' InitializeComponent()
objctx = New BanksDomainContext
Dim itemType = Branch_NameComboBox.SelectedItem.GetType
Dim pi = itemType.GetProperty(Branch_NameComboBox.DisplayMemberPath)
Dim cbi = pi.GetValue(Branch_NameComboBox.SelectedItem, Nothing).ToString()
Dim BranchName As String = cbi
' Dim query As EntityQuery(Of Branches) = objctx.GetBranchesDetailsQuery(BranchName)
' Dim loadOp As LoadOperation(Of Branches) = Me.objctx.Load(query)
' DataGrid1.ItemsSource = loadOp.Entities
' objctx.Load(query, LoadData, Nothing)
Dim loadOp = Me.objctx.Load(Me.objctx.GetBranchesDetailsQuery(BranchName))
LoadData(loadOp)
End Sub
Private Sub LoadData(lo As LoadOperation)
For Each br As Branches In lo.Entities
AddressTextBlock.Text = br.Address
CoordinatesTextBlock.Text = br.Coordinates
ManagerTextBlock.Text = br.Manager
PhoneTextBlock.Text = br.Phone
FaxTextBlock.Text = br.Fax
Next
End Sub
can someone guide me on how to do it?
The following is the solution to load text boxes from SQL records by selecting the search term from a list box:
Private Sub Branch_NameComboBox_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles Branch_NameComboBox.SelectionChanged
m_PushpinLayer.Children.Clear()
objctx = New BanksDomain
Dim itemType = Branch_NameComboBox.SelectedItem.[GetType]()
Dim pi = itemType.GetProperty(Branch_NameComboBox.DisplayMemberPath)
Dim cbi = pi.GetValue(Branch_NameComboBox.SelectedItem, Nothing).ToString()
Dim BranchName As String = cbi
Dim itemType2 = NameComboBox.SelectedItem.[GetType]()
Dim pi2 = itemType2.GetProperty(NameComboBox.DisplayMemberPath)
Dim cbi2 = pi2.GetValue(NameComboBox.SelectedItem, Nothing).ToString()
Dim BankName As String = cbi2
Dim bb As EntityQuery(Of Branches) = From b In objctx.GetBranchesDetailsQuery(BranchName) Where b.Bank = BankName Select b
Dim res As LoadOperation(Of Branches) = objctx.Load(bb, New Action(Of LoadOperation(Of Branches))(AddressOf GetBeansCompleted), True)
End Sub
Private Sub GetBeansCompleted(args As LoadOperation(Of Branches))
For Each bc As Branches In args.Entities
'
Dim Latitude As Double = bc.Lat
Dim Longitude As Double = bc.Lon
Dim CoO As Location = New Location
CoO.Latitude = Decimal.Parse(Latitude)
CoO.Longitude = Decimal.Parse(Longitude)
Dim BName As String = bc.Branch_Name.ToString
Dim MKColor As Color = GetThisColor(bc.MapKeyColor.ToString)
AddPushPin(BName, CoO, MKColor)
AddressTextBlock.Text = (bc.Address.ToString)
LatTextBlock.Text = (Decimal.Parse(Latitude))
LonTextBlock.Text = (Convert.ToDecimal(Longitude))
ManagerTextBlock.Text = (bc.Manager.ToString)
PhoneTextBlock.Text = (bc.Phone.ToString)
FaxTextBlock.Text = (bc.Fax.ToString)
Next
End Sub