2013年10月9日 星期三

[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);

2 則留言:

  1. 直接交給 javascript 去清某個條件裡面所有的input值會不會輕鬆一點?也可以有一定的彈性。

    回覆刪除
    回覆
    1. Hi 91 大,謝謝您的回覆,的確抽到前端搭配JQuery selector會輕鬆很多,因為這有點算是舊系統技術債的問題XD,很多寫法都很仰賴後端(邪惡的Postback),短時間之內不想動太多程式所以那時候很單純的修改後端邏輯後做個小筆記

      謝謝您的建議 ^_^

      刪除