How to clear all form fields from code-behind?(如何从代码隐藏中清除所有表单字段?)
问题描述
HTML 有一种输入按钮类型,可以一步将表单中的所有字段重置为其初始状态:<input type="reset" .../>.
HTML has an input button type to reset all fields in a form to their initial state in one step: <input type="reset" ... />.
是否有类似的简单方法可以从代码隐藏中重置 aspx 页面的所有表单字段?还是需要用TextBox1.Text=string.Empty、TextBox2.Text=string.Empty等一一重置所有控件?
Is there a similar simple way to reset all form fields of an aspx page from code-behind? Or is it necessary to reset all controls one by one with TextBox1.Text=string.Empty, TextBox2.Text=string.Empty, etc. ?
提前致谢!
更新:
Context 是一个简单的 Contact/Send us a message" 页面,页面上有 8 个 asp:TextBoxes(用户在其中输入姓名、地址、电话、电子邮件、消息等).然后他点击提交,代码隐藏中的 Onclick 消息处理程序向某个管理员发送一封电子邮件,用户填写的所有表单字段都应该被清空,他会在标签中收到通知(消息已发送 blabla...").我希望清除表单字段以避免用户再次单击提交并再次发送相同的消息.
Context is a simple Contact/"Send us a message" page with 8 asp:TextBoxes on the page (where the user enters the name, address, phone, email, message, etc.). Then he clicks on submit, the Onclick message handler in code-behind sends an email to some administrator, and all the form fields the user filled in should be emptied and he gets a notification in a label ("Message sent blabla..."). I want to have the form fields cleared to avoid that the user clicks again on submit and the same message is sent a second time.
推荐答案
您只需为每种类型的控件编写一个分支,除非其中一个控件有一些特殊的事情需要执行以重置它.
You need only write a fork for each type of control unless one of the control has something special that needs to be done to reset it.
foreach( var control in this.Controls )
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
...
}
附加您询问了如何清除隐藏的控件.为此,您应该像这样创建一个递归例程:
ADDITION You asked how to clear controls even ones that are buried. To do that, you should create a recursive routine like so:
private void ClearControl( Control control )
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
...
foreach( Control childControl in control.Controls )
{
ClearControl( childControl );
}
}
因此,您可以通过传递页面来调用它:
So, you would call this by passing the page:
ClearControls( this );
这篇关于如何从代码隐藏中清除所有表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从代码隐藏中清除所有表单字段?
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
