开发者

Adding Text to command buttons on runtime

开发者 https://www.devze.com 2022-12-17 19:01 出处:网络
I have 14 command buttons on my 开发者_如何学Goform. what i want to do is change the text of the form based on the current date.

I have 14 command buttons on my 开发者_如何学Goform. what i want to do is change the text of the form based on the current date. button1 should have todays date. button2 should have tommorows date. button3 should have day after tomorrows date and so on. I want this for fourteen buttons.

I can do it manually by assigning each button.text to each date... i want to do it using a loop. is it possible. my buttons are named , button1,button2,button3,button4, and so on toll button 14. and the text i want on them is from the current date to 14 days later... basiocally want to display the dates on the button.. is it possible though a loop. m using visual studio and vb.net


You could try something like

Dim dateVal As DateTime = DateTime.Today
For i As Integer = 1 To 14
    Dim but As Control = Controls("button" & i)
    but.Text = dateVal.ToString("dd MMM yyyy")
    dateVal = dateVal.AddDays(1)
Next


For Each b As Control In Me.Controls
    If TypeOf b Is Button Then
        Dim i As Integer = CInt(b.Name.Replace("Button", ""))
        If i <= 14 Then
            Dim d As DateTime = DateTime.Now.AddDays(i - 1)
            b.Text = d.ToString("dd MMM yyyy")
            d = d.AddDays(1)
        End If
    End If
Next

Place the code in the load event.


You can loop through the controls collection on your form, and if the control type is a button, you can code some rules around that.


Private Sub ApplyDateLabelsToButtons()

    Dim tmpDate As Date = DateTime.Today

    For i As Integer = 1 To 14
        Me.Controls("Button" & i.ToString()).Text = tmpDate.ToShortDateString()
        tmpDate = DateAdd(DateInterval.Day, 1, tmpDate)
    Next

End Sub


Try something like this:

I wrote it in C#:

private void Form1_Load(object sender, EventArgs e)
        {
            int v = 0;

            foreach(Control myBtn in this.Controls)
                if (myBtn is Button)
                {
                    myBtn.Text = DateTime.Today.AddDays(v).ToString();
                    v++;
                }
        }

Then was reminded you need it in VB.net, so here it is in vb.net:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) 
    Dim v As Integer = 0 

    For Each myBtn As Control In Me.Controls 
        If TypeOf myBtn Is Button Then 
            myBtn.Text = DateTime.Today.AddDays(v).ToString() 
            v += 1 
        End If 
    Next 
End Sub 
0

精彩评论

暂无评论...
验证码 换一张
取 消