Conor Datta
Conor Datta

Reputation: 23

Is it possible to pass textboxes as a parameter?

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;
}

Upvotes: 2

Views: 385

Answers (5)

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

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";
    }
}

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34152

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)

Upvotes: 3

isaeid
isaeid

Reputation: 553

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

(Convert.ToInt32(tb_viewIngredient1.Text)

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

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)

Upvotes: 0

Jeremy Thompson
Jeremy Thompson

Reputation: 65534

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) {

Upvotes: 0

Related Questions