I am using Visual Basic in Visual Studio 2017. I am trying to create buttons from a text file. If a text file contains words like
Test1
Test2
Test3
etc it should create 3 buttons using those names.
Dim path As String = "c:\words.txt"
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
Dim button As New System.Windows.Forms.Button()
Dim buttonTop As Integer = 100
For Each s In readText
Dim Location As New Point(100, (buttonTop + 20))
button.Location = Location
button.Text = s
button.Width = 100
Me.Controls.Add(button)
buttonTop += 20
button.Visible = True
Next
This code creates the buttons but are not saved. As the loop goes it creates them and they disappear from the form leaving just the last one at the end of the loop.
Any guidelines will be appreciated. Thanks.
Correct Answer. Thanks
Dim path As String = "c:\words.txt"
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
Dim buttonTop As Integer = 20
For Each s In readText
Dim button As New System.Windows.Forms.Button()
Dim Location As New Point(100, (buttonTop + 30))
button.Location = Location
Button.Text = s
button.Width = 100
button.Height = 30
Me.Controls.Add(Button)
buttonTop += 30
button.Visible = True
Next
Related
I'm trying to check some CheckBoxes programatically.
I read this post to do it.
How To Get Control Property by "String Name"?
My code:
1)
Dim FiltrosStr As String = AnswerX.Substring(7)
Dim Filt13() As String = FiltrosStr.Split(",")
If Filt13.Length >= 2 Then
Dim Filt1 = Filt13(0)
Dim Filt3 = Filt13(1)
x = 1
For Each XBit As Char In Filt1
Dim ChkName As String = "Filt" & x.ToString & "xxEvtVerChk"
Dim ChkX As CheckBox = Me.Controls.Find(ChkName, True).FirstOrDefault()'<-Halt here
If XBit = "1" Then
ChkX.Checked = True
Else
ChkX.Checked = False
End If
x += 1
If x > 6 Then
Exit For
End If
Next
2) Also tried
Dim x As Integer
Dim FiltrosStr As String = AnswerX.Substring(7)
Dim Filt13() As String = FiltrosStr.Split(",")
If Filt13.Length >= 2 Then
Dim Filt1 = Filt13(0)
Dim Filt3 = Filt13(1)
x = 1
For Each XBit As Char In Filt1
Dim ChkName As String = "Filt" & x.ToString & "xxEvtVerChk"
Dim ChkX As CheckBox = CType(Me.Controls(ChkName), CheckBox)'<-Halt here
If XBit = "1" Then
ChkX.Checked = True
Else
ChkX.Checked = False
End If
x += 1
If x > 6 Then
Exit For
End If
Next
I just need to check or uncheck some checkboxes that are inside a three level TabPage
Form-> TabPage-> TabPage-> TabPage-> GroupBox-> CheckBox
The 12 Check Boxes have almost the same name, only changes one number in the middle of it names.
I don't understand what I doing wrong and why even the IDE get halted.
The only way to stop it is by closing the session or restart Windows.
I have a For loop which runs through xlsx files in a directory, I need to append the filenames in a TextBlock after each loop and refresh the TextBlock to show the updated text.
The code I have below only displays the filenames after the loop has executed.
Dim lcFileName As String = ""
Dim fileArray() As String = Directory.GetFiles(txtDirectory.Text, "*.xlsx", SearchOption.AllDirectories)
For Each file As String In fileArray
Dim ExcelApp As Excel.Application = New Excel.Application
Dim Workbook As Excel.Workbook = ExcelApp.Workbooks.Open(file)
Dim Worksheet As Excel.Worksheet = Workbook.Sheets(1)
Dim Range As Excel.Range = Worksheet.UsedRange
Dim rowCount As Integer = Range.Rows.Count
Dim colCount As Integer = Range.Columns.Count
Dim tmpOrder(rowCount, colCount) As String
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(file) + " imported."
For i = 1 To rowCount
For j = 1 To colCount
'New line
If (i = 1 And j = 1) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value
lcFileName = tmpOrder(i - 1, j - 1).ToString()
Else
If (Not String.IsNullOrEmpty(Range.Cells(i, j).Value)) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value.ToString()
End If
End If
Next
Next
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Worksheet)
Worksheet = Nothing
ExcelApp.ActiveWorkbook.Close(True)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Workbook)
Workbook = Nothing
ExcelApp.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelApp)
ExcelApp = Nothing
'
Next
Any help would be appreciated, VB.Net required.
Finally got it working.
Ok first I created my Method to update the TextBlock with the parameter passed for the filename.
Public Sub UpdateResults(ByVal lcFile As String)
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(lcFile) + " imported."
End Sub
In my For Loop i called the method with the following code
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(Sub() Me.UpdateResults(lcFile)))
Where UpdateResults(lcFile) is the method and parameter passed.
If you are not passing any parameters then call your method using this, where 'MyMethod' is the name of the method you want to run.
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(AddressOf MyMethod))
Something isn't playing nicely and is preventing the form from updating.
You can allow the app to process pending display operations by adding Application.DoEvents() inside one of the loops.
There is some overhead involved, so you probably want it in the outer loop, not the inner loop.
I'm having a bit of a problem. Granted, I'm not the best with VB, but I can't figure out for the life of my why this isn't working.
I have an Access database that I pull data from. I'm trying to dynamically create labels so I can present the data as prettily as I want. However, when trying to execute it, I'm getting an exception "System.NullReferenceException: Object reference not set to an instance of an object" on the line arrayLabels(i).Text = "Howdy"
I'm almost certain it's something stupidly simple that I'm just missing... but here's my code:
Private Sub TabControl2_Click(sender As Object, e As EventArgs) Handles TabControl2.Click, btnRefresh1.Click, btnRefresh2.Click, btnRefresh3.Click, ddSelectTech.SelectedIndexChanged, ddSelectTech2.SelectedIndexChanged
If TabControl2.SelectedIndex = 0 Then
'use this to count the number of rows
Dim numRows As Integer
'here be database stuff
Dim da2 As OleDb.OleDbDataAdapter
Dim ds2 As New DataSet
Dim con2 As New OleDb.OleDbConnection
con2.ConnectionString = dbProvider & dbSource
sqlStatusOpen = "SELECT * FROM work_orders WHERE status = 'In Progress';"
da2 = New OleDb.OleDbDataAdapter(sqlStatusOpen, con2)
con2.Open()
da2.Fill(ds2, "installations2")
con2.Close()
numRows = ds2.Tables("installations2").Rows.Count()
'create an array label based on the number of rows in the table
Dim arrayLabels(numRows) As Label
'loop it to actually make the labels, position them, and such
For i = 0 To (numRows - 1) 'just looping the number of rows
Dim x As Integer = 100
Dim y As Integer = 1 + (i * 10)
Try
TabPage3.Controls.Add(arrayLabels(i))
arrayLabels(i).Text = "Howdy"
arrayLabels(i).Location = New Point(x, y)
Catch ex As Exception
MessageBox.Show(ex.ToString, "Looky there, Franky, another error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
ElseIf TabControl2.SelectedIndex = 1 Then
ElseIf TabControl2.SelectedIndex = 2 Then
Else
End If
End Sub
Of course, if you think there are better ways to handle this, I'm open to suggestions.
Your code:
Dim arrayLabels(numRows) As Label
Creates an array with the type Label. But every entry in this array is null.
Try to initialize every label in your loop:
Dim label As New Label
label.Text = "Howdy"
label.Location = New Point(x, y)
TabPage3.Controls.Add(label)
And you don't need to save the labels inside an array.
I have and array and i want to check if my Dim value is contains in array but i need to check if it appears twice.
Example:
Dim value as String = "AST"
Dim zone_check_list() As String = {"AMST","AST","AST","EET","EDT"}
'if "AST" appeared twice then i will show message box
How about using LINQ :
Imports System.Linq
Dim value as String = "AST"
Dim zone_check_list() As String = {"AMST","AST","AST","EET","EDT"}
Dim isAppearTwice As Boolean = (zone_check_list.Count(Function(x) x = value) = 2)
Console.WriteLine(isAppearTwice)
In winForms adding a CSV to a DataGrid was quite easy. I am now trying to add this to a Silverlight DataGrid. Here is my attempt - which yields 3 columns Capacity|Count|Items - mind you the values are correct 83|83|_ on each row. There are 83 rows, but the columns should be 23 with diff values in each. Thanks for looking and enjoy your bounty!
Code:
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
Dim srsCol As New List(Of List(Of String))
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
While Not sr.Peek = -1
srsCol.Add(New List(Of String)(sr.ReadLine.Split(","c).ToList))
End While
End Using
End Using
dgStaff.ItemsSource = srsCol
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
I decided to use the BindableDataGrid from CodePlex Since the binding is being set dynamically I had to come up with a Random string generator and assign that for the binding and all is well.
csvDs.Tables.Clear()
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
csvDs.Tables.Add(csvDt)
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
Dim i As Integer
While Not sr.EndOfStream
If i = 0 Then
Dim cols = sr.ReadLine.Split(","c)
For ii As Integer = 0 To cols.Count - 1
Dim rndValue As String = RndColName()
Dim col As New BindableDataGrid.Data.DataColumn(rndValue)
rndValues.Add(rndValue)
col.DataType = GetType(System.String)
col.Caption = ii.ToString
col.ReadOnly = True
col.AllowReorder = False
col.AllowResize = False
col.AllowSort = False
csvDt.Columns.Add(col)
AddItemsToCb(ii)
Next
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
Dim s As String = cols(_i).Replace("""", String.Empty)
row(rndValues(_i)) = s
csvValues.Add(s)
Next
csvDt.Rows.Add(row)
Else
Dim cols = sr.ReadLine.Split(","c)
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
row(rndValues(_i)) = cols(_i).Replace("""", String.Empty)
Next
csvDt.Rows.Add(row)
End If
i += 1
End While
End Using
End Using
dgStaff.DataSource = csvDs
dgStaff.DataMember = "csvTable"
dgStaff.DataBind()