我觉得太复杂了吗?如何简化这段代码?

时间:2010-05-20 09:41:10

标签: vb.net

有时候,我相信我的想法太复杂,或者只是厌倦了太多的思考或其他你可能指出的事情。

我正在尝试复制YouTube中的寻呼机,以获取我的Windows窗体应用程序。

这就是我到目前为止所做的事情:

Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, btn6.Click, btn7.Click, btnNext.Click
        If sender.text = "previous" Then
            SelIndex -= 1
        ElseIf sender.text = "next" Then
            SelIndex += 1
        Else
            If sender.text > SelIndex Then
                If sender.name = "btn5" OrElse sender.name = "btn6" OrElse sender.name = "btn7" Then
                    btn1.Text += 1
                    btn2.Text += 1
                    btn3.Text += 1
                    btn4.Text += 1
                    btn5.Text += 1
                    btn6.Text += 1
                    btn7.Text += 1
                    SelIndex = btn4.Text
                Else
                    SelIndex = sender.text
                End If
            ElseIf sender.text < SelIndex Then
                If sender.name = "btn1" OrElse sender.name = "btn2" OrElse sender.name = "btn3" Then
                    If btn1.Text <> "1" Then
                        btn1.Text -= 1
                        btn2.Text -= 1
                        btn3.Text -= 1
                        btn4.Text -= 1
                        btn5.Text -= 1
                        btn6.Text -= 1
                        btn7.Text -= 1
                        SelIndex = btn4.Text
                    Else
                        SelIndex = sender.text
                    End If
                End If
            Else
                SelIndex = sender.text
            End If
        End If
        Select Case SelIndex
            Case 1
                btnPrevious.Visible = False
            Case Else
                btnPrevious.Visible = True
        End Select
        Label1.Text = SelIndex
    End Sub

第一个问题似乎是我在沙滩上制作圈子。我不喜欢我编写代码的方式并且没有按预期工作。

所以问题是:我怎么能简化这个呢?

1 个答案:

答案 0 :(得分:0)

首先确定新页面,然后在按钮等上设置文本。类似的东西:

Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrevious.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, btn6.Click, btn7.Click, btnNext.Click
  If sender.text = "previous" Then
    SelIndex -= 1
  ElseIf sender.text = "next" Then
    SelIndex += 1
  Else
    SelIndex = Int32.Parse(sender.text)
  End If
  Dim buttons As Button() = { btn1, btn2, btn3, btn4, btn5, btn6, btn7 }
  For i As Integer = 0 to buttons.Length - 1
    Dim page As Integer = SelIndex + i - 3
    If page >= 1 Then
      buttons(i).Visible = True
      buttons(i).Text = page.ToString
    Else
      buttons(i).Visible = Flase
    End If
  Next
  btnPrevious.Visible = SelIndex > 1
  Label1.Text = SelIndex
End Sub