I'm attempting to pass the name of 2 textboxes into a method so that it edits the text in them. I have tried looking for examples online but can only find people attempting to pass textbox text through.
I've tried passing it in by declaring the text boxes in the method constructor.
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;
}
After running the code I expect the text box text to be changed to the appropriate value, instead I get this error about the textboxes in the call.
"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'"
Really sorry if there's an easy fix for this, but please point me in the right direction. Thanks in advance.
Real Code
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;
}
Yes it is possible:
void MyMethod(string str, TextBox txt)
{
txt.Text = str + " some text from the method itself";
}
You may even return a TextBox:
TextBox MyFunc(string str)
{
TextBox txt = new TextBox();
txt.Text = str;
return txt;
}
You are trying to convert TextBox into Int32:
Convert.ToInt32(tb_viewIngredient1)
which is not parsable to Int32. You may convert it's text to int32 (if it has a numeric value and can be parsed) like:
int.Parse(tb_viewIngredient1.Text)
or
Conver.ToInt32(tb_viewIngredient1.Text)