2012-06-28 30 views
1

我有一個表單,其中一些輸入,其中一些使用'title'屬性在輸入內部放置暗示文本。提交表單時,會發送一封電子郵件,其中包含每個輸入的值。但是,如果該字段未填寫,它將使用標題作爲值。我可以手動檢查空字段和刪除值,如下所示:ASP.NET C#清除控制空值

if (a_eventSelect.Attributes["title"] == a_eventSelect.Value) 
    { 
      a_eventSelect.Value = ""; 
    } 

的問題即如果該形式具有許多輸入檢查每一個可能成爲不必要地繁瑣。我開始製作一個函數來檢查每個控件並清除它是否爲空。

protected void Page_Load(object sender, EventArgs e) 
{ 
    //initialize 
    base.Initialize(); 

    //on reload of page 
    if (IsPostBack) 
    { 
      //clear blank values 
      clear(mainform); 

      //send email 
      SendEmail(); 

      //display thank you 
      thankyou.Visible = true; 

      //hide main 
      main.Visible = false; 
     } 
} 

public void clear(Control location) 
{ 
    //for each control in location 
    foreach (Control c in location.Controls) 
    { 
      //if the control has child controls 
      if (c.HasControls()) 
      { 
       //call function with new location 
       clear(c); 
      } 
      //some code to check value and title 
    } 
} 

似乎我無法弄清楚是如何再取每個控制實際上比較一下標題和值,甚至在函數中改變它的值。有沒有人有任何想法可以幫助?提前致謝。

回答

1

迭代在主窗體控件,強制轉換爲「根」級(我想控制將做到這一點),然後檢查他們

+0

我不知道我明白你說的要做什麼。 –

0

答案是基於兩點,我注意到

  1. 你想清除所有輸入控件
  2. 的代碼行(a_eventSelect.Attributes [「標題」] == a_eventSelect.Value)說,你在你的網頁表單

考試使用HtmlInputControl ple將設置值爲空

private void SetControlValueToEmpty() 
    { 
     IEnumerable<HtmlInputControl> htmlInputControls = form1.Controls.OfType<System.Web.UI.HtmlControls.HtmlInputControl>(); 
     foreach (var htmlInputControl in htmlInputControls) 
     { 
      if (htmlInputControl.Attributes["title"] == htmlInputControl.Value) 
      { 
       htmlInputControl.Value = ""; 
      } 
     } 
    } 
+0

每當我使用消息框來檢查這是哪個控件影響時,唯一出現的控件是'回傳'。你有什麼想法,爲什麼這是? –