【发布时间】:2020-04-24 12:04:28
【问题描述】:
我正在根据 SQL 表中的结果动态创建一组单选按钮。 SQL 结果存储在数据表中;有两列,一列用于客户端 ID,另一列用于客户端名称。每当用户激活此表单时,他们应该只看到客户端名称,但是当他们单击确定时,需要将 ID 值返回给一个变量。
我目前只传入表格中的 Client_Name 字段。如何返回客户端名称的 ID 值?是否可以为每个单独的按钮分配两个值?
创建按钮的代码:
//radio button array is initially set in the designer.cs file.
public System.Windows.Forms.RadioButton[] radioButtons { get; set; }
public Clients()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.FixedSingle;
//Call connectDatabase method from ContractSearch
ContractSearch con = new ContractSearch();
string database = "dbo";
string query = @"select distinct
client_id
,client_name
from
tbl_Clients";
DataTable result = con.connectToDatabase(database, query);
int client_row = result.Select().Length;
radioButtons = new RadioButton[client_row];
Label title = new Label();
title.Text = "Select a Client:";
int i = 0;
int y = 0;
title.Location = new Point(10, 10 + y * 20);
Controls.Add(title);
y += 1;
//Iterate through all rows in table, creating radio buttons for each client name value
foreach (DataRow cell in result.Rows)
{
radioButtons[i] = new RadioButton();
radioButtons[i].Text = cell["Client_Name"].ToString();
radioButtons[i].Location = new Point(10, 10 + y * 20);
Controls.Add(radioButtons[i]);
i += 1;
y += 1;
}
//create OK button
Button but_ok = new Button();
but_ok.Location = new Point(15, 10 + y * 25);
but_ok.Text = "OK";
Controls.Add(but_ok);
but_ok.Click += new EventHandler(this.but_ok_Click);
}
这是确定按钮的单击事件。这是我正在检查以确定单击了哪个单选按钮的地方。
private void but_ok_Click(object sender, EventArgs e)
{
//lookup enumerations to pass in id values to AA screen
foreach (RadioButton btn in radioButtons)
{
if(btn.Checked==false)
{
continue; //skip to next loop iteration if radio button is not checked
}
else if(btn.Checked==true)
{
Console.WriteLine(btn.Checked.ToString()+" "+btn.Text); //for debugging purposes
/*
store Client_ID value into but_value. This will be passed to the parent form.
radioButtons.Value does not serve a function. It is merely a placeholder.
*/
but_Value = radioButtons.Value;
}
}
Close();
}
【问题讨论】:
-
我很好奇
radioButtons是什么? -
这是单选按钮数组。它在设置所有属性的 deigner.cs 文件中设置。我更新了帖子以添加它。感谢您提出来。
标签: c# winforms radio-button