嘿我试图创建一个类似......的方法。
private void btnSubmit_Click(object sender, EventArgs e)
{
FillIn();
}
private void FillIn()
{
if (txtName.Text == "")
{
txtName.Text = "Bob Frank";
}
if (txtAddress.Text == "")
{
txtAddress.Text = "4111 N Pensyvania Ave.";
}
if (txtCity.Text == "")
{
txtCity.Text = "Longbeach";
}
if (txtState.Text == "")
{
txtState.Text = "CA";
}
if(txtZip.Text == "")
{
txtZip = "90210";
}
}
这段代码效果很好但是当我尝试像这样添加参数时..
private void btnSubmit_Click(object sender, EventArgs e)
{
FillIn(txtName.Text, txtStreetAddress.Text, txtCity.Text, txtState.Text, txtZip.Text);
}
private void FillIn(string name, string address, string city, string state, string zip)
{
if (name == "")
{
name = "Bob Frank";
}
if (address == "")
{
address = "4111 N Pensyvania Ave.";
}
if (city == "")
{
city = "Longbeach";
}
if (state == "")
{
state = "CA";
}
if(zip == "")
{
zip = "99210";
}
}
它停止工作,文本框不会重新填写并输出错误,我该如何解决?
答案 0 :(得分:3)
您需要传递实际控件。如果您尝试传递txtName.Text,它只是读取属性中的值而您无法更新它。
private void btnSubmit_Click(object sender, EventArgs e)
{
FillIn(txtName, txtStreetAddress, txtCity, txtState, txtZip);
}
private void FillIn(TextBox name, TextBox address, TextBox city, TextBox state, TextBox zip)
{
if (name.Text == "")
{
name.Text = "Bob Frank";
}
if (address.Text == "")
{
address.Text = "4111 N Pensyvania Ave.";
}
if (city.Text == "")
{
city.Text = "Longbeach";
}
if (state.Text == "")
{
state.Text = "CA";
}
if(zip.Text == "")
{
zip.Text = "99210";
}
}