[ASP.NET]C#清掉所有控制項的值

[ASP.NET]C#清掉所有控制項的值

分享一個小技巧,今天在維護舊系統發現一段程式,主要邏輯是處理完一些事後,要將某區塊的表單欄位清掉,程式很直覺但寫起來會很煩:

.aspx

<!-- 拉一些常用的Controll -->
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem>1</asp:ListItem>
    <asp:ListItem>2</asp:ListItem>
</asp:DropDownList>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<asp:Button ID="btn_Clear" runat="server" Text="Button" OnClick="btn_Clear_Click" />

.aspx.cs

TextBox1.Text = "";
Label1.Text = "";
DropDownList1.Items.Clear();
CheckBox1.Checked = false;

因為實際上控制項很多,所以就一拖拉庫以上的程式Orz,所以花了一點時間重構此塊,寫成一個function:

/// <summary>清掉控制項的值</summary>
/// <param name="ctols">控制項ID</param>
private void ClearControlValue(params Control[] ctols)
{
    foreach (Control ctol in ctols)
    {
        string cType = ctols.GetType().Name;
        if (typeof(TextBox).Name == cType)
        {
            (ctol as TextBox).Text = string.Empty;
        }
        else if (typeof(DropDownList).Name == cType)
        {
            (ctol as DropDownList).Items.Clear();
        }
        else if (typeof(CheckBox).Name == cType)
        {
            (ctol as CheckBox).Checked = false;
        }
        else if (typeof(CheckBoxList).Name == cType)
        {
            (ctol as CheckBoxList).SelectedIndex = -1;
        }
        else if (typeof(RadioButton).Name == cType)
        {
            (ctol as RadioButton).Checked = false;
        }
        else if (typeof(RadioButtonList).Name == cType)
        {
            (ctol as RadioButtonList).SelectedIndex = -1;
        }
        else if (typeof(Label).Name == cType)
        {
            (ctol as Label).Text = string.Empty;
        }
    }
}

使用方法:

//把要清掉值的控制項ID傳入
ClearControlValue(TextBox1, CheckBoxList1, Label1);