如何将字符串转换为WebControl.Button

时间:2016-07-02 13:00:56

标签: jquery asp.net vb.net

我有超过100个asp.net按钮,我需要直接从数据库设置BackColor和Text,如果我能解决这个问题,我可以用大约10行代码替换400+行Select语句。以下转换方法都不起作用,如果有,我可以用If子句中的var b.ID替换c

    Sub Page_Load(sender As Object, e As EventArgs)
    Dim taR As New DsReadyTableAdapters.taReady
    Dim dtR As New DsReady.ReadyDataTable
    taR.Fill(dtR)
    Dim x As Integer = 1
    Dim ss As String
    Dim t As Type
    For Each b In form1.Controls
        t = b.GetType
        If t.Name = "Button" Then
            Dim c As System.Web.UI.WebControls.Button = CType(b.ID, System.Web.UI.WebControls.Button) 'tried both, doesn't work
            Dim c As System.Web.UI.WebControls.Button = DirectCast(b.ID, System.Web.UI.WebControls.Button) 'tried both, doesn't work
            ss = CStr(b.ID).Substring(6)
            If ss > 122 And ss < 126 Then
                b.ID.BackColor = Drawing.ColorTranslator.FromHtml(dtR(x).Color) 'b.ID is string so doesn't work
                b.ID.Text = dtR(x).Num
                x += 1
            End If
        End If
    Next b
End Sub 

我还尝试在Controls.OfType语句中使用For Each子句将结果缩小到仅按钮,但无济于事。我也愿意用jQuery做这个,但是没有找到一种直接的方法从数据库中提取数据就像我正在使用的一样简单。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

Dim button As Button = CType(form1.Controls["your_button_name"], Button)

答案 1 :(得分:0)

实际上我发现jQuery提供了一种直接简单的方法来实现这一点,在这种情况下迭代HTML元素,按钮。将类名添加到您尝试查找的按钮中。谢谢你的帮助。

function dealer() {  // for Deal
        var i = 0;
        $('.deal').each(function(){ //need class="deal"
            var chit = deal[i];
            if (chit.length == 2) {
                var v = chit.slice(0, 1);
                var c = chit.slice(1);
            } else { // 3
                var v = chit.slice(0, 2);
                var c = chit.slice(2);
            }
            (this.value) = v; // Number
            switch (c) {
                case "r":
                    (this.style.backgroundColor) = "red";  // Color
                    break;
                case "b":
                    (this.style.backgroundColor) = "lightblue";
                    break;
                case "g":
                    (this.style.backgroundColor) = "gray";
                    break;
                case "o":
                    (this.style.backgroundColor) = "orange";
                    break;
            } // switch
            i++;
            event.preventDefault();
        }); //deal
    }; // dealer