使用循环更改属性

时间:2019-03-22 14:04:55

标签: vb.net loops

我想知道是否有一种使用循环压缩代码的方法,这是我的代码: (Cell_1_Containes是RichTextBox)

    Cell_1_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 1\Containes.txt")
    Cell_2_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 2\Containes.txt")
    Cell_3_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 3\Containes.txt")
    Cell_4_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 4\Containes.txt")
    Cell_5_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 5\Containes.txt")
    Cell_6_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 6\Containes.txt")
    Cell_7_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 7\Containes.txt")
    Cell_8_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 8\Containes.txt")
    Cell_9_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 9\Containes.txt")
    Cell_10_Containes.Text = My.Computer.FileSystem.ReadAllText(MyLocation + "\Main\Cells\Cell 10\Containes.txt")

1 个答案:

答案 0 :(得分:1)

Dim cells() As Control = {Cell_1_Containes, Cell_2_Containes,Cell_3_Containes,Cell_4_Containes,Cell_5_Containes,Cell_6_Containes,Cell_7_Containes,Cell_8_Containes,Cell_9_Containes,Cell_10_Containes}
For i As Integer = 0 To 9
    cells(i).Text = My.Computer.FileSystem.ReadAllText(Path.Combine(MyLocation, $"Main\Cells\Cell {i+1}\Containes.txt"))
Next