I want to Count how many times I click a button and display the number, but the format should be like: 0001 if reach 9999 restart to 0001 again and count till 9999.
I tried:
Private ButtonClickCount As Integer = 0
ButtonClickCount += 1
Label5.Text = "0000" & ButtonClickCount
And
Label5.Text = "0000" + Val(Label5.Text) + 1
This was the dumbest way I tried.lol
And the result was disapointing.
Is there any easy way to do it?
If you use a Static variable for the count, you can keep it in the button click event handler. (Static variables aren't used all that often, but it works here, assuming you don't need the variable anywhere else.)
If you check if the counter has reached 10000, you can set it back to 1.
You can format the number in the .ToString method.
Perhaps something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static clickCount As Integer = 0
clickCount += 1
If clickCount = 10000 Then
clickCount = 1
End If
lblClickCount.Text = clickCount.ToString("0000")
End Sub
You could use the Format command, which controls how many zeroes you want in the output:
Dim ButtonClicks As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ButtonClicks += 1
Label1.Text = Format(ButtonClicks, "0000")
End Sub
Dim ButtonClicks As Integer = 0
Private sub Button1_click(sender as object, e as EventArgs) handles Button 1.click
Buttonclick +=1
If buttonclick ="9999" then
Buttonlclick=1
Endif
Label1.text =format(Buttonclick, "0000")
End sub
You will need to keep track of the counter somewhere, in this case I would suggest storing the counter in the control's Tag property (documentation). In your button's click event, you would do the following:
Get the Tag
Convert the value to an Integer
Increment the value by 1
Check if the new value is greater than 9999
Optionally reset the value to 1 if 4 is true
Set the Text of the Button to the formatted result
Set the Tag of the button to the new value
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim clickedButton = DirectCast(sender, Button)
Dim tagValue = clickedButton.Tag
If (tagValue Is Nothing) Then
tagValue = 0
End If
Dim conversion As Integer
If (Not Integer.TryParse(tagValue.ToString(), conversion)) Then
conversion = 0
End If
conversion += 1
If (conversion > 9999) Then
conversion = 1
End If
clickedButton.Text = converstion.ToString("0000")
clickedButton.Tag = conversion
End Sub
Well, sorry guys, just realized that I could use the PadLeft function... And worked fine.
ButtonClickCount += 1
Label5.Text = ButtonClickCount.ToString().PadLeft(5, "0")
But Still don't know if it reaches 9999 will restart from 0001
Related
sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub
How can Set the Progress Bar Value increasing/ decreasing according to data entered in each controls on a form ? I mean, I am working with number of controls, so go for a sample [Suppose I have four textboxes, Progress Bar Maximum 100, when entering txt_1 Progress value have to increase to 100/4= 25, if I remove data from txt_1 the Value should decreased to Zero.
Sorry for my language, I am not good in English.
Can any one help me, please..... Thank You.
The Firs thing you do is set the progressbar maximum in your formload event to the number of textboxes you are using.
Dim TextBoxNumber As Integer = 4
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Maximum = TextBoxNumber
End Sub
Then you need to make 2 events.
1. TextBox enter event."Private Sub TextBox_Enter(sender As Object, e As EventArgs)"
2. TextBox TextChanged event"Private Sub TextBox_TextChanged(sender As Object, e As EventArgs)"
Then Link all the textboxes you want to use to the events.
In these events you will use the Sender.
Make a Dim and convert the sender to type Textbox to use its properties." Dim TextControl As TextBox = CType(sender, TextBox)"
In the Enter event you count the text that is entered in the textbox.
If the count is 0 you set the boolean to true and if its more than 0 you set the Boolean to False.
This Boolean you will use in the Text Change event.
Dim CheckTextBox As Boolean
Private Sub TextBox_Enter(sender As Object, e As EventArgs) Handles TextBox4.Enter, TextBox3.Enter, TextBox2.Enter, TextBox1.Enter
Dim TextControl As TextBox = CType(sender, TextBox)
If TextControl.Text.Count > 0 Then
CheckTextBox = False
Else
CheckTextBox = True
End If
End Sub
In the Text Change event you need to do a few things.
1.Use a if statement to check if the textbox is empty."This will only trigger if the user deletes the text in the textbox."
So if empty remove 1 from the progressbar and set CheckTextBox"Boolean" to True
"ProgressValue = ProgressValue - 1"
"CheckTextBox = True"
2.Then use a ElseIf to check if the CheckTextBox"Boolean" is True.
If true add 1 to progressbar and set Boolean to false.
"ProgressValue = ProgressValue + 1"
"CheckTextBox = False"
You need to set the Boolean to false because otherwise you will add 25 for every time you add somthing to the textbox.
Dim ProgressValue As Integer
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextChanged, TextBox3.TextChanged, TextBox2.TextChanged, TextBox1.TextChanged
Dim TextControl As TextBox = CType(sender, TextBox)
If TextControl.Text = "" Then
ProgressValue = ProgressValue - 1
CheckTextBox = True
ElseIf CheckTextBox = True Then
ProgressValue = ProgressValue + 1
CheckTextBox = False
End If
ProgressBar1.Value = ProgressValue
End Sub
hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub
I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub
This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Label1.Text.Length = 13 Then
Label1.Text = "Working magic."
ElseIf Label1.Text.Length = 14 Then
Label1.Text = "Working magic.."
ElseIf Label1.Text.Length = 15 Then
Label1.Text = "Working magic..."
ElseIf Label1.Text.Length = 16 Then
Label1.Text = "Working magic"
End If
End Sub
The code basically acting as a progressive string, where every 500 milliseconds a dot will add to the string, until 3 dots where it resets.
If I wanted to do more dots then it would be nice to automate the process, instead of writing an infinite number of lines of code.
If you want to shorten your code you could do something like this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
(Label1.text += ".").Replace("....","")
End Sub
However I'm convinced that shorter is not always better!
Edit: Sorry my mind goes straight to c#, here is some VB::
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.text = (Label1.text + ".").Replace("....","")
End Sub
Pseudo code:
len = Label1.Text.Length - 12
str = "Working magic"
while(len>0 && len<4){
str = str & "."
len--;
}
Label1.Text = str
Pseudo code that takes into account the variable number of dots in a row.
final NUM_DOTS = 3 //this is your variable number of dots
len = Label1.Text.Length - 12
str = "Working magic"
numDots = NUM_DOTS
while(len){
if (numDots == 0) {
str = str.substring(0, str.length-NUM_DOTS);
numDots = NUM_DOTS;
}
else {
str = str & "."
len--;
numDots--;
}
}
Label1.Text = str
easy, console apps demo
Module Module1
Sub Main()
Console.WriteLine(Magic(New String("A"c, 13).Length))
Console.WriteLine(Magic(New String("A"c, 14).Length))
Console.WriteLine(Magic(New String("A"c, 15).Length))
Console.WriteLine(Magic(New String("A"c, 16).Length))
Console.Read()
End Sub
Private Function Magic(ByVal len As Integer) As String
Dim result = "Working magic"
Select Case len
Case 13 To 15
result = result & New String("."c, len - 12)
End Select
Return result
End Function
End Module
Consider using animated GIFs like those generated here: http://www.ajaxload.info/
Try Google Search for more options: "animated gifs generator"
Just use the GIF in a picture box and use .Enable/.Visible to manage.
The animation can be stalled if the main thread is busy - probably true for the above cases as well.
Keep the count of dots to print as a global variable, then at every call of the timer event increment this value and reset it if it reaches the upper limit.
Create a string of dots based on the current count and append it to the static label
Private dotCount As Integer = 0
Const MAX_DOTS = 3
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
if dotCount > MAX_DOTS Then
dotCount = 0
End If
Label1.Text = "Working magic" & new String(".", dotCount)
dotCount = dotCount + 1
End Sub
If you want to print more dots, just change the constant used as upper limit (MAX_DOTS)
A new issue !!
I have a checkbox column in the datagridview and also a column named "partqty" which displays the quantity of materails available.. I would want that when the user checks on the checkbox, the quantities of checked rows should be added and displayed in the textbox..
I tired something like this.. But it displays 0(zero) in the textbox.. Please help..
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
'For Each _rw As DataGridViewRow In dataGridView1.Rows
' If _rw.Cells(0).Value = True Then
Dim totalSum As Integer
For i As Integer = 0 To HemDatabase1DataSet5.Tables(0).Rows.Count - 1
totalSum += HemDatabase1DataSet5.Tables(0).Rows(i).Item("partqty")
Next
textBox5.Text = totalSum.ToString()
' End If
'Next
End Sub
Hey !! This is something i could think upon trying !! however, there is no error during compile time, but there is an error at runtime, which says :
Operator '+' is not defined for type 'DBNull' and type 'Boolean'
Here is the code i tried :
For Each _rw As DataGridViewRow In dataGridView1.Rows
If _rw.Cells(0).Value = True Then
Dim totalSum As Integer
For i As Integer = 0 To dataGridView1.Rows.Count - 1
totalSum += dataGridView1.Rows(i).Cells(5).Value
Next
textBox5.Text = totalSum.ToString()
End If
Next
It gives error on this line :
totalSum += dataGridView1.Rows(i).Cells(5).Value
You first problem is that you are trying to add apples and oranges together.
In the line:
totalSum += dataGridView1.Rows(i).Cells(5).Value
totalSum is an integer while the Value property of a DataGridView cell is of type object.
This is a similar problem to what you see when trying to use the DataTable except there your Item property is givin you a DBNull rather than an object back.
Here is the code that you want (I'm mainly a C# dev so the VB.Net might be lacking elegance but it works).
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim sum As Integer
sum = 0
For Each row As DataGridViewRow In DataGridView1.Rows
Dim current As Integer
If Integer.TryParse(row.Cells("OrderQty").Value.ToString, current) Then
sum += current
End If
Next
TextBox1.Text = sum.ToString
End Sub
Some things worth noting about that code:
I use a For Each rather than a for. The two perform basically identically but I find the foreach more readable
I use Integer.TryParse on the cell value before using it. This is safer than just casting the cell value directly.
Rather then using column indexes which is a little fragile I use column names.
With your check on whether or not the checkbox is checked you can do something similar:
Boolean.TryParse(row.Cells("IsChecked").Value.ToString, cb)
One final point to note is that if you try to execute this code in the cellclick method of the DataGridView you will run into problems - the checkbox state is not committed until after the cellclick, so the most recently checked cell will not get added to your count. Instead you will want to handle the CellDirtyStateChanged and commit the edits, then doing the sum in the CellValueChanged handler.
To illustrate that try this code:
Private Sub dgv_CellContentClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim sum As Integer
sum = 0
Dim cb As Boolean
cb = False
If DataGridView1.Columns(e.ColumnIndex).Name <> "IsChecked" Then
Return
End If
For Each row As DataGridViewRow In DataGridView1.Rows
If Boolean.TryParse(row.Cells("IsChecked").Value.ToString, cb) Then
If cb Then
Dim current As Integer
If Integer.TryParse(row.Cells("OrderQty").Value.ToString, current) Then
sum += current
End If
End If
End If
Next
TextBox1.Text = sum.ToString
End Sub
The sum will always lag one click behind (actually in VB.Net it appears to just nor really work - but I'm more a c# dev so that could be me missing something).
Instead you want:
Sub dataGridView1_CurrentCellDirtyStateChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles DataGridView1.CurrentCellDirtyStateChanged
If DataGridView1.IsCurrentCellDirty Then
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
' If a check box cell is clicked, this event handler disables
' or enables the button in the same row as the clicked cell.
Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellValueChanged
If DataGridView1.Columns(e.ColumnIndex).Name = "IsChecked" Then
Dim sum As Integer
sum = 0
Dim cb As Boolean
For Each row As DataGridViewRow In DataGridView1.Rows
If Boolean.TryParse(row.Cells("IsChecked").Value.ToString, cb) Then
If cb Then
Dim current As Integer
If Integer.TryParse(row.Cells("OrderQty").Value.ToString, current) Then
sum += current
End If
End If
End If
Next
TextBox1.Text = sum.ToString
End If
End Sub
This is the code that worked..
Dim iSselected As Boolean
Dim CurrentCellValue As String
Dim CumulativeSummer As Integer
Dim i As Integer
With Me.dataGridView1
For i = 0 To .RowCount - 1
iSselected = .Rows(i).Cells(0).Value
CurrentCellValue = .Rows(i).Cells(5).Value
If CurrentCellValue = "" Then CurrentCellValue = 0
If iSselected = True Then
CumulativeSummer += Convert.ToInt32(CurrentCellValue)
End If
Next
End With
Me.textBox5.Text = CumulativeSummer
Thank u for your help !! :)