覆盖Text属性设置为自动微调文本框的值 [英] Override Text Property to auto trim Textbox value
问题描述
我要重写文本的文本框将其值设置为自动修剪的
属性。对于这一点,我不得不定义以下类:
I want to override the Text
property of a textbox to set its value as auto trimmed. For that, I had to define the following class:
public class TextBox : System.Web.UI.WebControls.TextBox
{
public override string Text
{
get { return base.Text.Trim(); }
//Automatically trim the Text property as it gets assigned
set { base.Text = value.Trim(); }
}
}
但问题是,它不工作在设计页面(的.aspx)定义的文本框,它仅适用于动态创建的文本框。
But the issue is that it's not working for TextBoxes defined in a design page (.aspx) and it only works for dynamically created Textboxes.
我需要这样code返回无论是动态或静态地增加了对所有文本框一个修整值。
I need such code that returns a trimmed value for all TextBoxes whether it is added dynamically or statically.
我该如何解决这个问题?
How can I fix this?
推荐答案
您应该创建一个自定义的控制,并给它一个不同的名称。
You should create a custom control and give it a different name.
[DefaultProperty("Text")]
[ToolboxData("<{0}:TrimmedTextBox runat=server></{0}:TrimmedTextBox>")]
public class TrimmedTextBox : TextBox
{
[Category("Appearance")]
public override string Text
{
get { return base.Text.Trim(); }
//Automatically trim the Text property as it gets assigned
set { base.Text = value.Trim(); }
}
}
在此之后,打开你的AssemblyInfo.cs,并在底部添加以下行:
After this, open your AssemblyInfo.cs and add the following line at the bottom:
//[assembly: TagPrefix("yournamespace", "aspCustom")]
[assembly: TagPrefix("WebformsSandbox", "aspCustom")]
//change "aspCustom" to the prefix of your choice!
在这你的工具应该可以在设计时:
After this your tool should be available at design-time:
要拨打标记code您的自定义的元素,无论是从工具箱中绘制到code或写:
To call your Custom element in markup code, either draw it from the toolbox into the code or write:
<aspCustom:TrimmedTextBox ID="TrimmedTextBox1" runat="server"></aspCustom:TrimmedTextBox>
//修改
我已经 p.campbell 发现了另一个可行的解决方案在这里:的查找一个页面所有文本框控件
//EDIT I have found another working solution here by p.campbell: Find all textbox control in a page
这避免了在所有创建自定义元素。你要做的就是在您的扩展类中定义helpermethod:
This avoids creating a custom element at all. What you do is define a helpermethod in your Extensions class:
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
您已经这样做了之后,你可以在你的所有TextBox控件的页面上迭代,并修剪文本:
After you have done this, you can iterate over all your Textbox controls on your page and trim the text:
foreach (var t in this.Controls.FindAll().OfType<TextBox>())
{
t.Text = t.Text.Trim();
}
您应该能够过滤此更通过其中(T =方式&gt; t.Id.Contains(someValue中)
或任何你喜欢
You should be able to filter this even more by using Where(t => t.Id.Contains("someValue")
or whatever you like.
您认为更好的是什么给你。
What you deem better is up to you.
这篇关于覆盖Text属性设置为自动微调文本框的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!