我该如何优化代码

时间:2014-05-03 19:58:40

标签: asp.net vb.net repeater

我有以下代码行:

 Protected Sub RepComisiones_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles RepComisiones.ItemDataBound
    Dim valoresRepeter As DataRowView


    If e.Item.ItemType = ListItemType.Item Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
        valoresRepeter = e.Item.DataItem

        Select Case valoresRepeter("ECO").ToString
            Case "0"
                CType(e.Item.FindControl("lblEco"), Label).Text = ""
        End Select
        Select Case valoresRepeter("A").ToString
            Case 0
                CType(e.Item.FindControl("lblA"), Label).Text = ""
        End Select
        Select Case valoresRepeter("B1").ToString
            Case 0
                CType(e.Item.FindControl("lblB1"), Label).Text = ""
        End Select
        Select Case valoresRepeter("B2").ToString
            Case 0
                CType(e.Item.FindControl("lblB2"), Label).Text = ""
        End Select
        Select Case valoresRepeter("B3").ToString
            Case 0
                CType(e.Item.FindControl("lblB3"), Label).Text = ""
        End Select
        Select Case valoresRepeter("B3P").ToString
            Case 0
                CType(e.Item.FindControl("lblB3P"), Label).Text = ""
        End Select

    End If
End Sub

我想减少一些行,我尝试不同的方法,但结果不正确,任何想法如何优化。

谢谢

1 个答案:

答案 0 :(得分:1)

一个简单而干净的解决方案是将所有键(“ECO”,“A”,“B1”)及其相应的控件名称(“lblECO”,“lblA”,“lblB”)放入字典中并迭代通过这个来评估个人情况。

Private mappings As New Dictionary(Of String, String) From
        {
            {"ECO", "lblEco"},
            {"A", "lblA"},
            {"B1", "lblB1"}
        }

Sub RepComisiones_ItemDataBound()

        For Each key As String In mappings.Keys
            If valoresRepeter(key).ToString Is "0" Then
                DirectCast(e.Item.FindControl(mappings.Item(key)), Label).Text = ""
            End If
        Next

    End Sub