如何转换字符串来控制“名称”数据类型?
问题描述:
我有一个名为“customer.cs”的窗体,其中我有一个名为“phonetxt”的文本框,我在名为myclass.cs的模型中有一个类,我在“customer.cs”中有一行代码 ,如何转换字符串来控制“名称”数据类型?
private void customerphone_Leave(object sender, EventArgs e)
{
if (customerphone.Text != "Enter Phone Number" && customerphone.Text == "")
{
this.customerphone.Text = "Enter Phone Number";
this.customerphone.ForeColor = Color.DarkGray;
errorcustomerphone.Icon = Properties.Resources.err;
errorcustomerphone.SetError(customerphone, "Enter Phone Number");
}
else
{
errorcustomerphone.Icon = Properties.Resources.ok;
errorcustomerphone.SetError(customerphone, "Enter Phone Number");
}
}
我想,这将在customer.cs调用
methodfortext("customerphone","errorcustomerphone","Enter PhoneNumber");
//that will send these parameters to myclass.cs
methodfortext(string controlname, string errorname , string name)
{
//i want
controlname.Text = name;
errorname.Icon = Properties.Resources.err;
}
有人请帮助我的方法,我在C#。希望新ü人得到了我想要的东西。
答
这可能是一个很好的起点。
using System.Windows.Forms;
public static class ErrorHelper
{
public static void SetError(Form form, string controlName, string errorProviderName, string errorMessage)
{
var textBox = GetControl<TextBox>(form, controlName);
if (textBox != null)
{
textBox.Text = errorMessage;
}
// If you create an ErrorProvider control by code
// do not forget to add it to the form controls collection
// by calling this.Controls.Add(errorProvider); in the form class
// otherwise, it will not be found this way.
var errorProvider = GetControl<ErrorProvider>(form, controlName);
if (errorProvider != null)
{
errorProvider.Icon = Properties.Resources.err;
}
}
private static T GetControl<T>(Form form, string controlName) where T : Control
{
foreach (object control in form.Controls)
{
var ctl = control as Control;
if (ctl != null && String.Equals(ctl.Name, controlName))
return ctl as T;
}
}
}