#XVAL shows data index (integer) instead of string of an array - vb.net

I want to know why #XVAL shows the index (from 0 to 3 since there is 4 items in there) instead of ex:"< .50%" and so on. This will help me to change the desired output, which is "< .50%".
I've tried #AXISLABEL too and it doesn't work.
Here is a snippet of the code:
Private Sub LoadGraphicChart()
Try
C1Chart2.ChartGroups(0).ChartData.SeriesList.Clear()
' Data
Dim items As String() = New String() {"< 0.50%", "0.50% - 1.00%", "1.00% - 2.00%", "> 2.00%"}
Dim unitHData As Double() = New Double() {7 / 100, 0, 0, 1 / 100}
'first try, populating the series
Dim unitH As C1.Win.C1Chart.ChartDataSeriesCollection = C1Chart2.ChartGroups(0).ChartData.SeriesList
'unitH.Clear()
Dim series As ChartDataSeries = unitH.AddNewSeries
series.Label = "Unit Holder"
series.LineStyle.Color = Color.MediumPurple
series.X.CopyDataIn(items)
series.Y.CopyDataIn(unitHData)
'tooltip
C1Chart2.ToolTip.Enabled = True
For Each ds As ChartDataSeries In unitH
ds.TooltipText = "Series = {#TEXT}" + ControlChars.Cr + ControlChars.Lf + "X = {#XVAL}" + ControlChars.Cr + ControlChars.Lf + "Y = {#YVAL:0.00%}"
Next ds
End Try
End Sub
This is what the tooltip currently looks like:

Changing from using tooltiptext to CoordToDataIndex solved my problems.
Here is how I use it:
Private Sub C1Chart2_MouseClick(sender As Object, e As MouseEventArgs) Handles C1Chart2.MouseClick
Dim SeriesOutput As Integer
Dim PointOutput As Integer
Dim DistanceOutput As Integer
Dim items As String() = New String() {InputLabel10.Text, InputLabel9.Text, InputLabel8.Text, InputLabel7.Text}
Dim unitHData As String() = New String() {FormatPercent((CDbl(lblPersen00.Text) / 100)), FormatPercent((CDbl(lblPersen05.Text) / 100)), FormatPercent((CDbl(lblPersen10.Text) / 100)), FormatPercent((CDbl(lblPersen20.Text) / 100))}
C1Chart2.ChartGroups.Group0.CoordToDataIndex(e.X, e.Y, CoordinateFocusEnum.XandYCoord, SeriesOutput, PointOutput, DistanceOutput)
Debug.WriteLine("Series Index : " & SeriesOutput.ToString())
Debug.WriteLine("Point Index : " & PointOutput.ToString())
Debug.WriteLine("Distance from Point: " & DistanceOutput.ToString())
'MessageBox.Show(PointOutput)
If PointOutput.ToString <> "" Then
MessageBox.Show("X : " & items(PointOutput) & ControlChars.Cr & ControlChars.Lf & "Y : " & unitHData(PointOutput))
End If
End Sub
Result(First Data):
Result(Last Data):

Related

How to print datagridview data in horizontal line with printdocument?

I have a query in the SqlServer database, the result of that query is played inside a Datagridview, the result can contain from 0 to 100 data or even more if you doubt it.
I'm trying to print the "Identification" column of Datagridview horizontally, but without success. I have researched in several places and nothing too.
screenshot of form with DataGridView
Follow the form code:
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.Drawing.Printing
Public Class frm_relatorio_entregas
' Variables used in the module
Dim RelatorioTitulo As String ' Report title
Dim paginaatual As Integer ' Page number being printed
Dim LinhaAtual As Integer ' Current line number being printed
Dim LinhasporPagina As Integer ' Number of lines per page
Dim PosicaoDaLinha As Single ' Position of the line being printed
Dim registro As Integer ' Record being printed
Private Sub Imprimir()
RelatorioTitulo = "Delivery Report"
Dim doc As PrintDocument = New PrintDocument
AddHandler doc.PrintPage, New Printing.PrintPageEventHandler(AddressOf Me.pdRelatorios_Printpage)
AddHandler doc.BeginPrint, New Printing.PrintEventHandler(AddressOf Me.Begin_Print)
Dim dialogo As PrintDialog = New PrintDialog
'dialogo.Document = doc
' If (dialogo.ShowDialog = DialogResult.OK) Then
Dim preview As PrintPreviewDialog = New PrintPreviewDialog()
preview.Document = doc
preview.WindowState = FormWindowState.Maximized
preview.PrintPreviewControl.Zoom = 1.0
preview.ShowDialog()
'End If
End Sub
Private Sub Begin_Print(ByVal sender As Object, ByVal e As Printing.PrintEventArgs)
' Assigning values ​​to variables at the start of printing
LinhaAtual = 0
paginaatual = 1
PosicaoDaLinha = 0
registro = 0
End Sub
Private Sub pdRelatorios_Printpage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
' Margin variables (e.MarginBounds obtain the rectangular area that represents the part of the page within the margins.)
Dim MargemEsquerda As Single = e.MarginBounds.Left
Dim MargemDireita As Single = e.MarginBounds.Right
Dim MargemSuperior As Single = e.MarginBounds.Top
Dim MargemInferios As Single = e.MarginBounds.Bottom
'Pen class defines an object used to define lines and curves
Dim CanetaDaImpressora As Pen = New Pen(Color.Black, 1)
'Variables of the fonts used (the font class defines a specific format for text, including font face, size and style attributes.
Dim FonteNegrito As Font
Dim FonteTitulo As Font
Dim FonteSubTitulo As Font
Dim FonteRodape As Font
Dim FonteNormal As Font
Dim font1 As Font
'Define effects on fonts used
FonteNegrito = New Font("Arial", 9, FontStyle.Bold)
FonteTitulo = New Font("Arial", 13, FontStyle.Bold)
FonteSubTitulo = New Font("Arial", 9, FontStyle.Bold)
FonteRodape = New Font("Arial", 8)
FonteNormal = New Font("Calibri", 9)
font1 = New Font("Segoe UI", 8, FontStyle.Bold)
'Print the title of the report
e.Graphics.DrawString(RelatorioTitulo, FonteTitulo, Brushes.Black, MargemEsquerda + 200, 30, New StringFormat)
If DateTimePicker1.Value = DateTimePicker1.Value Then
e.Graphics.DrawString(DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
Else
e.Graphics.DrawString(DateTimePicker1.Value & " - " & DateTimePicker1.Value, FonteSubTitulo, Brushes.Black, MargemEsquerda + 900, 30, New StringFormat)
End If
'Define the number of lines per page
LinhasporPagina = CInt(e.MarginBounds.Height / New Font("Calibri", 18).GetHeight(e.Graphics) - 2)
While (LinhaAtual <= LinhasporPagina AndAlso registro <= DataGridView1.Rows.Count - 1)
PosicaoDaLinha = MargemSuperior + (LinhaAtual * New Font("Calibri", 18).GetHeight(e.Graphics) + 30)
e.Graphics.DrawString(DataGridView1.Rows(registro).Cells(0).Value.ToString, New Font("Calibri", 8, FontStyle.Bold), Brushes.Black, 30, PosicaoDaLinha, New StringFormat())
'Increment record
registro += 1
'increment line
LinhaAtual += 1
End While
'baseboard
e.Graphics.DrawLine(CanetaDaImpressora, 20, MargemInferios + 15, 1150, MargemInferios + 15)
e.Graphics.DrawString(System.DateTime.Now.ToString(), FonteRodape, Brushes.Black, 30, MargemInferios + 15, New StringFormat())
e.Graphics.DrawString("Página : " & paginaatual, FonteRodape, Brushes.Black, 1070, MargemInferios + 15, New StringFormat)
'Increase the page number
paginaatual += 1
'Here check if you are going to open a new page
If (LinhaAtual > LinhasporPagina) Then
' When you open a new page, you have to reset LlinhaAtual
e.HasMorePages = True
LinhaAtual = 0
Else
e.HasMorePages = False
End If
End Sub
Private Sub frm_relatorio_entregas_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtcod.Clear()
txtrazao.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
ComboBox1.SelectedIndex = 0
txtcod.Select()
End Sub
Private Sub txtcod_KeyUp(sender As Object, e As KeyEventArgs) Handles txtcod.KeyUp
If e.KeyCode = Keys.F2 Then
frm_consulta_cliente_cadastro.ShowDialog()
End If
End Sub
Private Sub consulta()
DataGridView1.Rows.Clear()
Cursor.Current = Cursors.WaitCursor
Dim consultando As New frm_aguarde_consultando
consultando.Show()
' Set cursor as hourglass
Application.DoEvents()
Dim ano, mes, dia As Integer
Dim var1data, var2data As Date
Dim dinicio, dfim As String
var1data = DateTimePicker1.Value '.ToString.Substring(0, 10)
dia = var1data.Day
mes = var1data.Month
ano = var1data.Year
dinicio = ano & "-" & mes & "-" & dia
var2data = DateTimePicker2.Value
dia = var2data.Day
mes = var2data.Month
ano = var2data.Year
dfim = ano & "-" & mes & "-" & dia
Using sqlcoon As SqlConnection = GetConnectionsql()
Dim READER As SqlDataReader
Try
sqlcoon.Open()
Dim Query As String
Query = "select MOV_IDENTIFICACAO,MOV_PROTOCOLO,MOV_DATADOC,MOV_SITUACAO,MOV_DATAENTREGA,MOV_HORAENTREGA,MOV_SITEND_CODIGO
from movimento where MOV_DATADOC = '" & dinicio & "'
AND MOV_CLI_CODIGO = '" & txtcod.Text & "' AND MOV_SITUACAO = '" & "E" & "'
AND CAST(MOV_DATAENTREGA AS DATE) = '" & dfim & "' "
Dim COMMAND As SqlCommand = New SqlCommand(Query, sqlcoon)
READER = COMMAND.ExecuteReader
While READER.Read
Dim MOV_IDENTIFICACAO = READER("MOV_IDENTIFICACAO")
Dim MOV_DATADOC = READER("MOV_DATADOC")
Dim MOV_DATAENTREGA = READER("MOV_DATAENTREGA")
Dim MOV_PROTOCOLO = READER("MOV_PROTOCOLO")
Dim MOV_SITUACAO = READER("MOV_SITUACAO")
Dim MOV_SITEND_CODIGO = READER("MOV_SITEND_CODIGO")
DataGridView1.Rows.Add(MOV_IDENTIFICACAO, MOV_PROTOCOLO, MOV_DATADOC, MOV_SITUACAO, MOV_DATAENTREGA, MOV_SITEND_CODIGO)
End While
READER.Close()
sqlcoon.Close()
''--------------'''''''''
Label9.Text = DataGridView1.Rows.Count
For Each linha In DataGridView1.Rows
Dim altura As Integer = 17
linha.height = altura
Next
If DataGridView1.Rows.Count >= 0 Then
' Set cursor as default arrow
Cursor.Current = Cursors.Default
' Hide the please wait form
consultando.Hide()
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
' sqlcoon.Dispose()
End Try
sqlcoon.Open()
Try
For r As Integer = 0 To DataGridView1.Rows.Count - 1
Dim COMMAND3 As SqlCommand
Dim READER3 As SqlDataReader
Dim Query_3 As String
Query_3 = "select IMOV_CODIGORECBTO from imovimento where IMOV_MOV_IDENTIFICACAO ='" & DataGridView1.Rows(r).Cells(0).Value.ToString & "'"
COMMAND3 = New SqlCommand(Query_3, sqlcoon)
READER3 = COMMAND3.ExecuteReader
While READER3.Read
Dim IMOV_CODIGORECBTO = READER3("IMOV_CODIGORECBTO")
'DataGridView1.Columns(6).HeaderCell.Value = "ID"
DataGridView1.Rows(r).Cells(6).Value = IMOV_CODIGORECBTO
End While
READER3.Close()
Next
DataGridView1.Sort(DataGridView1.Columns(6), ListSortDirection.Ascending)
sqlcoon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
consulta()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Imprimir()
End Sub
End Class
screenshot of what is currently being printed
screenshot of I would like the result to be:
Would anyone have any ideas, tools or means to help me? I thank.
An alternative would be to:
Get just the column values that you want.
Join the values from #1 using a delimiter, such as a tab.
Use the Graphics.DrawString method (documentation) for the value from #2.
There will need to be some considerations:
You will need to measure the string from #3 to see if it exceeds the bounds of your print document
If so, then you will need to print multiple pages, picking up where you left off.
Update
Per the OP's request, here is an example. Keep in mind that it doesn't account for the considerations listed above. That will take a bit of effort in debugging to account for those points:
Private Sub pdRelatorios_PrintPage(sender As Object, e As PrintPageEventArgs) Handles pdRelatorios.PrintPage
Dim title = "Relatorio de Entregas"
Dim titleFont = New Font(Font.FontFamily, Convert.ToSingle(Font.Size * 1.5), FontStyle.Bold)
Dim titlePosition = New PointF(Convert.ToSingle(e.MarginBounds.X * 2 - e.PageBounds.Width / 2), e.MarginBounds.Y)
Dim titleSize = e.Graphics.MeasureString(title, titleFont)
e.Graphics.DrawString(title, titleFont, SystemBrushes.ControlText, titlePosition)
Dim cellValues = DataGridView1.Rows.Cast(Of DataGridViewRow).Select(Function(row) row.Cells(0)?.Value?.ToString())
Dim joinedCellValues = String.Join(Constants.vbTab, cellValues)
Dim bodyBounds = New RectangleF(e.MarginBounds.X, Convert.ToSingle(titleSize.Height + e.MarginBounds.Y), e.PageBounds.Width - e.MarginBounds.X * 2, e.PageBounds.Height - e.MarginBounds.Y * 2)
e.Graphics.DrawString(joinedCellValues, Font, SystemBrushes.ControlText, bodyBounds)
End Sub

Find and highlight the max value in from multiple column in VB.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error
maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

Creating multiple labels and adding text in vb.net

I have a List of KeyValuePairs where the number of KeyValuePairs changes over time. In a form I need to create a label for each KeyValuePair that contains the Value as the text.
How can I do this?
This is what I have tried...
For Each element In keyvalueP
Dim Label1 As New Label
With Label1
.Width = 512
.Height = 18
.Left = 12
.Text = " Nr. " & i & " - Matchtype " & element.Value.ToString
End With
i = i + 1
Next
I actually manage to find a solution that worked
Private Sub R75Dialog_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim labelText = ""
Dim i = 0
For Each element In keyvalueP
labelText = " Nr. " & i & " Groupname: " & element.Key.ToString & " - Matchtype " & element.Value.ToString
Dim label As New Label()
Dim count As Integer = Panel1.Controls.OfType(Of Label)().ToList().Count
label.Location = New Point(10, (25 * count) + 2)
label.Size = New Size(1000, 20)
label.Name = "label_" & (count + 1)
label.Text = labelText
Panel1.Controls.Add(label)
i = i + 1
Next
End Sub

How to update a Progressbar / Label created per code in a for each loop?

First my code :
Sub festplatte()
Dim allDrives() As DriveInfo = DriveInfo.GetDrives()
Dim d As DriveInfo
Dim I As Integer
For Each d In allDrives
If d.IsReady = True Then
Try
' Intelize controls
Dim progressbar As ProgressBar = New ProgressBar
Dim pbgroup As GroupBox = New GroupBox
Dim info As Label = New Label
Dim type As Label = New Label
Dim format As Label = New Label
Dim Space As Double = d.TotalFreeSpace / d.TotalSize
' Add to tab
Me.Tab_M.Controls.Add(progressbar)
Me.Tab_M.Controls.Add(pbgroup)
Me.Tab_M.Controls.Add(info)
Me.Tab_M.Controls.Add(type)
Me.Tab_M.Controls.Add(format)
' Add to group
pbgroup.Controls.Add(progressbar)
pbgroup.Controls.Add(info)
pbgroup.Controls.Add(type)
pbgroup.Controls.Add(format)
pbgroup.Text = d.Name & " | Name : " & CheckName(d.VolumeLabel.ToString())
pbgroup.Size = New System.Drawing.Size(600, 65)
pbgroup.Location = New System.Drawing.Point(8, I * 70 + 40)
' format
format.AutoSize = True
format.Name = "format" & I
format.Location = New System.Drawing.Point(435, 36)
format.Text = "Format : " & d.DriveFormat
' Typ
type.AutoSize = True
type.Name = "type" & I
type.Location = New System.Drawing.Point(435, 16)
type.Text = "Art : " & GetDriverFormat(d)
' info
info.Name = "info" & I
info.Location = New System.Drawing.Point(6, 16)
info.AutoSize = True
' Info Text :: 1000 MB Grenze
If d.TotalFreeSpace > Math.Pow(1024, 3) Then
info.Text = "Benutzter Speicher beträgt : " & Math.Round((d.TotalSize - d.TotalFreeSpace) / btogb, 2) & " GB von " & Math.Round((d.TotalSize) / btogb, 2) & " GB (" & Math.Round(100 - Space * 100, 2) & " % )"
Else
info.Text = "Benutzter Speicher beträgt : " & Math.Round((d.TotalSize - d.TotalFreeSpace) / btomb, 2) & " MB von " & Math.Round((d.TotalSize) / btomb, 2) & " MB (" & Math.Round(100 - Space * 100, 2) & " % )"
End If
'Progressbar
progressbar.Size = New System.Drawing.Size(425, 23)
progressbar.Location = New System.Drawing.Point(6, 32)
progressbar.Name = "Memory" & I
progressbar.Value = 100 - Space * 100
Catch ex As Exception
MsgBox(ex.ToString())
End Try
I += 1
End If
Next
End Sub
The code does generate a groupbox with each a progressbar in it and 3 labels, where i would like to edit something.
How can I edit the text of for example a label ? And how could I add / remove generated elements from the form ? I tried with refresh but it doesnt work
The Form
This was something quick I tried:
Dim LabelList As New List(Of Integer)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim LBL As New Label
LBL.Location = New Point(6, 23)
LBL.AutoSize = True
Me.Controls.Add(LBL)
LabelList.Add(Me.Controls.Count - 1)
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.Controls(LabelList(0)).Text = "HELLO WORLD!"
End Sub
This will add a label to the form and then add it's control index to LabelList. LabelList(0) will get the index for the first added label.

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.