我想创建一个使用以下方法调用的方法:
methodname(textBoxX);
我想要它做的是改变textBoxX的属性,如
private void methodname(Object textbox)
{
tryparse (textbox.Text, out somevariable);
textbox.Text = something;
}
答案 0 :(得分:1)
是的,这是可能的。虽然,我会做Dmitry上面所说的并使用TextBox txtBx1
作为参数。通过这样做,您传入一个TextBox对象,然后可以访问所有TextBox方法和属性,即txtBx1.Text="some text"
。
答案 1 :(得分:1)
是的,但是您不需要将参数设为Object,只需将其设为TextBox即可。
答案 2 :(得分:0)
嗯......这个问题引发了很多其他问题,但是如果您想要检查传递给方法的object
是TextBox
,然后设置{{ 1}}属性,你需要:
Text
修改强>
现在正在进入我想问你为什么需要这个问题的领域,因为我所建议的可能不是问题的最佳答案,但我们走了。如果您想知道对象是否具有private void ChangeText(object target)
{
var tBox = target as TextBox;
if (tBox != null)
tBox.Text = "new value";
}
属性,并相应地设置该值,则可以使用此属性。
在我的* .aspx页面上,我有:
Text
我的<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox>
<asp:CheckBox runat="server" ID="CheckBox1" />
<asp:RadioButton runat="server" ID="RadioButton1" />
<asp:Panel runat="server" ID="Panel1"></asp:Panel>
事件如下所示:
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
ChangeText(TextBox1);
ChangeText(RadioButton1);
ChangeText(CheckBox1);
ChangeText(Panel1);
}
的实施如下:
ChangeText()
前三个元素修改了private void ChangeText(object target)
{
var textProperty = target.GetType().GetProperty("Text");
if (textProperty != null)
{
try
{
target.GetType().GetProperty("Text").SetValue(target, "New Value", null);
}
catch (Exception ex)
{
if (ex is ArgumentException
|| ex is MethodAccessException
|| ex is TargetInvocationException)
{
// Unable to set the property for whatever reason
return;
}
// All other exceptions -- something unexpected happened.
throw;
}
}
}
属性; Text
没有,因为那里没有Panel
属性。