我试图将 2 个文本框的名称传递到一个方法中,以便它编辑其中的文本。我尝试在网上寻找示例,但只能找到尝试传递文本框文本的人。
我尝试通过在方法构造函数中声明文本框来传递它。
MethodName(string text, tb_1, tb_2);
private void MethodName(string str, TextBox tb_name, TextBox tb_allergen)
{
string ingredientName = "";
string ingredientAllergen = "";
//code to change strings//
tb_name.Text = ingredientName;
tb_allergen.Text = ingredientAllergen;
}
运行代码后,我希望将文本框文本更改为适当的值,但我在调用中收到有关文本框的错误。
"An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible'"
真的很抱歉,如果有一个简单的解决方案,但请指出正确的方向。提前致谢。
真实代码
ingredientDBAccess ingredientDBA = new ingredientDBAccess(db);
populateBoxesWithIngredientResults( ingredientDBA.getIngredientsFromID(Convert.ToInt32(tb_viewIngredient1)), tb_viewIngredient1, tb_viewAllergen1);
private void populateBoxesWithIngredientResults(List<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
string ingredientName = "";
string ingredientAllergen = "";
foreach (ingredient ingredient in ingredientList)
{
string name = Convert.ToString(ingredient.IngredientName);
ingredientName = name;
string allergen = "N/A";
switch (ingredient.AllergenID)
{
case 0:
allergen = "N/A";
break;
case 1:
allergen = "Nut";
break;
case 2:
allergen = "Gluten";
break;
case 3:
allergen = "Dairy";
break;
case 4:
allergen = "Egg";
break;
}
ingredientAllergen = allergen;
}
tb_name.Text = ingredientName;
tb_allergen.Text = ingredientAllergen;
}
最佳答案
是的,这是可能的:
void MyMethod(string str, TextBox txt)
{
txt.Text = str + " some text from the method itself";
}
您甚至可以返回一个文本框:
TextBox MyFunc(string str)
{
TextBox txt = new TextBox();
txt.Text = str;
return txt;
}
您正在尝试将 TextBox 转换为 Int32:
Convert.ToInt32(tb_viewIngredient1)
无法解析为 Int32。您可以将其文本转换为 int32 (如果它具有数值并且可以解析),例如:
int.Parse(tb_viewIngredient1.Text)
或
Conver.ToInt32(tb_viewIngredient1.Text)
关于c# - 是否可以将文本框作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55407589/