【问题标题】:ASP.NET C# Clearing Null Values from ControlASP.NET C# 清除控件中的空值
【发布时间】:2012-06-30 08:54:01
【问题描述】:

我有一个包含各种输入的表单,其中一些使用“标题”属性将提示文本放入输入中。提交表单时,会发送一封电子邮件,其中包含每个输入的值。但是,如果该字段尚未填写,它将使用标题作为值。我可以检查一个空字段并像这样手动删除该值:

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
     }
}

我似乎无法弄清楚如何获取每个控件并实际比较它的标题和值,甚至在函数中更改它的值。有没有人知道什么可能会有所帮助?提前致谢。

【问题讨论】:

    标签: c# asp.net forms controls .net


    【解决方案1】:

    答案基于我注意到的两点

    1. 您想清除所有输入控件
    2. 代码行 (a_eventSelect.Attributes["title"] == a_eventSelect.Value) 表明您在网络表单中使用 HtmlInputControl

    将值设置为空的示例

        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 = "";
                }
            }
        }
    

    【讨论】:

    • 每当我使用消息框检查这会影响哪些控件时,出现的唯一控件是“回发”。你知道这是为什么吗?
    【解决方案2】:

    迭代主窗体控件,转换为“根”类(我认为 Control 会这样做),然后检查它们

    【讨论】:

    • 我不确定我是否明白你在说什么。
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多