-
Oct 26th, 2020, 01:26 PM
#1
Thread Starter
Member
[RESOLVED] conditional formatting of textbox font on a form
Hi,
Hope you are safe and well
I have a form which contains number of textboxes, among which 32 are populated by data grid values, which is turn is populated by a sql query. All this works fine, however what I would like is some kind of loop that goes through the text boxes and if the value is <0 then make that textbox font colour red and green if >= 0.
There are other textboxes on the form for example the title which I believe you wont be able to convert to integer if that's what is needed.
This will save me doing an if statement for every text box I would like to check.
Thank you in advance.
-
Oct 26th, 2020, 07:13 PM
#2
Re: conditional formatting of textbox font on a form
Firstly, if you're not already, you should be binding your data to both the grid and the TextBoxes, e.g.
vb.net Code:
myDataAdapter.Fill(myDataTable)
BindingSource1.DataSource = myDataTable
DataGridView1.DataSource = BindingSource1
TextBox1.DataBindings.Add("Text", BindingSource1, "SomeColumn")
The TextBoxes will then update automatically when you select a row in the grid and any changes you make in the TextBoxes will be automatically pushed to the data source and, therefore, reflected in the grid.
As for the question, forget about using a loop. Select all the desired TextBoxes in the designer, open the Properties window, click the Events button and then double-click the TextChanged event. That will create a single method to handle that event for all those controls. You can then add code that will be executed for that TextBox each time the Text in one changes, e.g.
vb.net Code:
Private Sub TextBoxes_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged,
TextBox2.TextChanged,
TextBox1.TextChanged
Dim tb = DirectCast(sender, TextBox)
Dim number As Integer
If Integer.TryParse(tb.Text, number) Then
If number < 0 Then
tb.ForeColor = Color.Red
Else
tb.ForeColor = Color.Green
End If
Else
tb.ForeColor = SystemColors.WindowText
End If
End Sub
Last edited by jmcilhinney; Oct 30th, 2020 at 08:20 PM.
-
Oct 30th, 2020, 06:09 PM
#3
Thread Starter
Member
Re: conditional formatting of textbox font on a form
Exactly what I wanted mate - your a star. Thank you ever so much, that was excellent
I am posting another similar question with regards to buttons - take a look if you have the time (grit teeth!!)
Thanks once again
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|