【问题标题】:Casting string + enum value to TextBox type将字符串 + 枚举值转换为 TextBox 类型
【发布时间】:2016-10-27 19:51:54
【问题描述】:

我目前在一个表单上有 14 个文本框(开发完成后将有多达 30 个)存储在数组“textBox”中。每个文本框代表竞争对手在其网站上宣传特定产品的价格。每个文本框的名称都以“txt”为前缀,然后是经销商名称。

在我的代码中,有很多对 textBox[i].Text、textBox[i].BackColor 等的操作,以及对相应标签('lbl' + 经销商名称)和变量('str' + 经销商名称)。

我想要做的是有一个经销商名称的枚举,然后在表单加载上将数组分配给每个项目对应于枚举中的一个项目。

类似:

 enum Dealers { DealerName1, DealerName2, DealerName3, DealerName4 etc..};
 string[] prices = new string[13];
 TextBox[] textBox = new TextBox[13];
 Label[] labels = new Label[13];

 for (int i = 0, i < 14, i++)
 {
      textBox[i] = txt + //Name of dealer at enum position i
      label[i] = lbl + //Name of dealer at enum position i
 }

 //do processing and assign prices variables

 for (int i = 0, i < 14, i++)
 {
      textBox[i].Text = prices[i]
 }

我的问题是在相关整数位置连接“txt”和枚举中的经销商名称的正确语法是什么,然后使用它来分配 textBox[i]

【问题讨论】:

    标签: c# enums


    【解决方案1】:

    您应该使用方法FindControl("IDOfControl")。 - 这是针对 .net 网络表单的

     for (int i = 0, i < 14, i++)
     {
          textBox[i] = (TextBox)FindControl("txt" + (Dealers)i)
          label[i] = (Label)FindControl("lbl" + (Dealers)i)
     }
    

    编辑:

    如果您正在编写 winforms,您应该使用 this.Controls.Find("IDOfYourControl", true)[0] 而不是 FindControl("") 方法。

    【讨论】:

    • 是否需要引用某个类才能在 .net WinForms 应用程序中使用 FindControl 方法?
    • 谢谢你应该在问题中指定它是winforms!
    • @TomCarroll 好的,首先控制数组-> this.Controls.Find("IDOfYourControl", true)[0]
    • 是的,这实际上很明显!在旁注中,您到底是如何在评论中编写代码
    猜你喜欢
    • 2018-02-14
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2010-10-03
    • 1970-01-01
    • 2021-07-21
    相关资源
    最近更新 更多