出處:
http://www.dotblogs.com.tw/kyleshen/archive/2013/10/10/123562.aspx
分享一個小技巧,今天在維護舊系統發現一段程式,主要邏輯是處理完一些事後,要將某區塊的表單欄位清掉,程式很直覺但寫起來會很煩:
.aspx
01 |
<!-- 拉一些常用的Controll --> |
02 |
< asp:TextBox ID = "TextBox1" runat = "server" ></ asp:TextBox > |
03 |
< asp:Label ID = "Label1" runat = "server" Text = "Label" ></ asp:Label > |
04 |
< asp:DropDownList ID = "DropDownList1" runat = "server" > |
05 |
< asp:ListItem >1</ asp:ListItem > |
06 |
< asp:ListItem >2</ asp:ListItem > |
08 |
< asp:HiddenField ID = "HiddenField1" runat = "server" /> |
09 |
< asp:CheckBox ID = "CheckBox1" runat = "server" /> |
10 |
< asp:CheckBoxList ID = "CheckBoxList1" runat = "server" ></ asp:CheckBoxList > |
11 |
< asp:Button ID = "btn_Clear" runat = "server" Text = "Button" OnClick = "btn_Clear_Click" /> |
.aspx.cs
3 |
DropDownList1.Items.Clear(); |
4 |
CheckBox1.Checked = false ; |
因為實際上控制項很多,所以就一拖拉庫以上的程式Orz,所以花了一點時間重構此塊,寫成一個function:
view source
print?
01 |
/// <summary>清掉控制項的值</summary> |
02 |
/// <param name="ctols">控制項ID</param> |
03 |
private void ClearControlValue( params Control[] ctols) |
05 |
foreach (Control ctol in ctols) |
07 |
string cType = ctols.GetType().Name; |
08 |
if ( typeof (TextBox).Name == cType) |
10 |
(ctol as TextBox).Text = string .Empty; |
12 |
else if ( typeof (DropDownList).Name == cType) |
14 |
(ctol as DropDownList).Items.Clear(); |
16 |
else if ( typeof (CheckBox).Name == cType) |
18 |
(ctol as CheckBox).Checked = false ; |
20 |
else if ( typeof (CheckBoxList).Name == cType) |
22 |
(ctol as CheckBoxList).SelectedIndex = -1; |
24 |
else if ( typeof (RadioButton).Name == cType) |
26 |
(ctol as RadioButton).Checked = false ; |
28 |
else if ( typeof (RadioButtonList).Name == cType) |
30 |
(ctol as RadioButtonList).SelectedIndex = -1; |
32 |
else if ( typeof (Label).Name == cType) |
34 |
(ctol as Label).Text = string .Empty; |
使用方法:
2 |
ClearControlValue(TextBox1, CheckBoxList1, Label1); |