2

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;
}
Community
  • 1
  • 1

5 Answers5

3

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)
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • I feel like this is similar to what i attempted, however mine just came up with an error stating " Unable to cast object of type 'System.Windows.Forms.TextBox' to type 'System.IConvertible' " – Conor Datta Mar 28 '19 at 22:42
  • Thanks so much for all your help, can't believe I didn't realise that to be honest. – Conor Datta Mar 28 '19 at 22:59
0

The problem is the in two places

MethodName(string theStringVariable, tb_1, tb_2);

private void MethodName(string theStringVariable, TextBox tb_name, TextBox tb_allergen) {

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
0

Convert.ToInt32(tb_viewIngredient1) will throw an exception because you're trying to convert a TextBox control to an int. Instead, try passing the Text property of the TextBox to the method:

Convert.ToInt32(tb_viewIngredient1.Text)
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

The problem is in (Convert.ToInt32(tb_viewIngredient1), you must convert it to:

(Convert.ToInt32(tb_viewIngredient1.Text)
isaeid
  • 543
  • 5
  • 26
  • I can't believe i was staring at that for 2 hours and it was that obvious. I was convinced that that part was fine and focusing on the other. Thanks so much to you and everyone who tried to help me in my stupidity – Conor Datta Mar 28 '19 at 22:50
  • Thanks, you can add points to helpful answers. The other friends also answered this solution. – isaeid Mar 28 '19 at 22:56
0

I see three different options here. Any of these would be better even than the fixed code, depending on what your needs are. All of them address two points:

  1. You can use a lookup table for the allergens rather than a switch. The resulting code is shorter/simpler and should run faster.
  2. You loop through every item in ingredientList, but the textboxes will only ever keep data from the last item in the list. Either look at just that last item (no need for a loop), or use all of the items in the list (ie: create csv strings). The loop as it is is wasteful and complicates the code.

.

private void populateBoxesWithIngredientResults(IEnumerable<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{
    string nameDelimiter = "";
    string allergenDelimiter = "";

    string ingredients = "";
    string allergens = "";

    var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};

    foreach (ingredient ingredient in ingredientList)
    {
        //Is Convert.ToString() really needed here?
        // I feel like ingredient.IngredientName is ALREADY A STRING
        ingredients += delimiter + Convert.ToString(ingredient.IngredientName);
        nameDelimiter = ",";

        if (ingredient.AllergenID > 0 && ingredient.AllergenID < allergenTable.Length)
        {
            allergens += allergenDelimiter + allergenTable[ingredient.AllergenID];
            allergenDelimiter = ",";
        }
    }
    if (allergens == "") allergens = "N/A";

    tb_name.Text = ingredients;
    tb_allergen.Text = allergens;
}

or

private void populateBoxesWithIngredientResults(IEnumerable<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{       
    tb_name.Text = string.Join(",", ingredientList.Select(i => i.IngredientName));

    var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};
    var allergens = ingredientList.
         Select(i => (i.AllergenID > 0 && i.AllergenID < allergenTable.Length)? allergenTable[i.AllergenID]):"").
         Where(i => i.Length > 0);
    var result = string.Join(",", allergens);
    if (string.IsNullOrEmpty(result)) result = "N/A";

    tb_allergen.Text = result;
}

or

private void populateBoxesWithIngredientResults(List<ingredient> ingredientList, TextBox tb_name, TextBox tb_allergen)
{    
    if (ingredientList.Length == 0)
    {
        tb_name.Text = "";
        tb_allergen.Text = "";
    }

    var allergenTable = {"N/A", "Nut", "Gluten", "Dairy", "Egg"};
    var ingredient = ingredientList[ingredientList.Count - 1];

    tb_name.Text = ingredient.IngredientName;  
    if (ingredient.AllergenID >= 0 && ingredient.AllergenID < allergenTable.Length)
    {
        tb_allergen.Text = allergenTable[ingredient.AllergenID];
    }
    else
    {
        tb_allergen.Text = "N/A";
    }
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794