不能从动态生成的单选按钮列表中读取值

本文关键字:列表 读取 单选按钮 动态 不能 | 更新日期: 2023-09-27 18:02:37

我正在尝试这样做:

  1. 从Windows注册表中读取多个值(works)。这看起来像

    'HKLM'...'Server1
    int serverid 1
    string serverName "SRVSQL01"
    int serverport 1433
    string database "MyDatabase1"
    'HKLM'...'Server2
    dword/int serverid 2
    regsz/string serverName "SRVSQL02"
    dword/int serverport 1433
    regsz/string database "MyDatabase2"
    
  2. 列表项。我可以从注册表中读取值,这很好

  3. 为c#类(works)的多个实例添加值

    我创建了一个类"SQLServer",有4个变量/值,如上所示。然后我创建这个类的多个实例的数组,例如,如果在注册表中列出了4个服务器,我生成一个长度为4的数组,并将每个服务器的值添加到该类的自己的实体中。

    public class RegSQLListItem
    {
        public int MSSSQLID;
        public string MSSQLServer;
        public int MSSQLPort;
        public string MSSQLDatabase;
    }
    
  4. 根据数组中"项目"的数量,通过生成单选按钮,在一个新的表单中显示列表。

    我在这里找到了一些代码来动态生成带有标签的单选按钮列表:https://msdn.microsoft.com/en-us/library/dwafxk44(v=vs.90).aspx

    // Generate form
    int ProjectCounter = (RegProjectRoot.GetSubKeyNames()).Count();
    // other code
    RadioButton[] radioButtons = new RadioButton[ProjectCounter];
    for (int i = 0; i < ProjectCounter; ++i)
    {
        radioButtons[i] = new RadioButton();
        radioButtons[i].TabIndex = i + 1;
        radioButtons[i].Name = ProjectListItem[i].MSSQLDatabase;
        radioButtons[i].Text = ProjectListItem[i].MSSQLDatabase;
        radioButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
        this.Controls.Add(radioButtons[i]);
    }
    

我如何捕获哪个单选按钮被选中,我如何将相应的值转移到我的程序中的另一个例程?

我特别感兴趣的是单击"确定"按钮来捕获当前活动的单选按钮的值,从而选择我要连接到哪个数据库。

这是正确的方法吗?还是有更简单的方法?

不能从动态生成的单选按钮列表中读取值

有两种方法:

1。添加如下事件处理程序:

for (int i = 0; i < ProjectCounter; ++i)
{
    radioButtons[i] = new RadioButton();
    radioButtons[i].TabIndex = i + 1;
    radioButtons[i].Name = "ProjectListItem[i].MSSQLDatabase";
    radioButtons[i].Text = "ProjectListItem[i].MSSQLDatabase";
    radioButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
    radioButtons[i].CheckedChanged += new EventHandler(rdo_CheckedChanged);
    this.Controls.Add(radioButtons[i]);
}

处理程序rdo_CheckedChanged将定义如下:

private static void rdo_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rdoButton = sender as RadioButton;
    if (rdoButton.Checked)
    { 
       // procced the button is checked
    }
}

2。遍历RadioButton类型的控件

您可以使用以下代码遍历控件并识别所选的单选按钮:

foreach (RadioButton rdo in this.Controls.OfType<RadioButton>())
{
    if (rdo.Checked)
    {
        // this is checked radio button
        // Proceed with your code
    }
}