c# - 是否可以将文本框作为参数传递?

标签 c# textbox parameter-passing

我试图将 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/

相关文章:

c# - 如何在 Reflection.Emit 中使用条件

html - 如何创建扩展文本框?

php - 选择时文本框更改

php - 如何在表单提交时保留已设置的 GET 参数值?

java - 将方法传递给 Java 中的基准测试程序

Python、SQLAlchemy 在 connection.execute 中传递参数

c# - Web API 中的 ContinueWith 死锁

c# - 在 C# 应用程序中使用现有的 C++ 代码

c# - 如何通过外键引用访问表数据?

c# - 文本框 : Modify user's input