创建radiobutton
//绘制界面
public void DrawInterface(DataTable dt)
{
if (dt == null ||dt.Rows.Count==0)
{
MessageBox.Show("数据为空,返回重新操作");
this.Close();
}
else
{
int dtLength = dt.Rows.Count;
Label[] l1 = new Label[dtLength];
RadioButton[] rb = new RadioButton[dtLength];
int topStep = 10;
for (int i = 0; i < dtLength; i++)
{
int leftStep = 100;
//
// radioButton
//
rb[i] = new RadioButton();
rb[i].AutoSize = true;
rb[i].Name =i.ToString();
rb[i].Left =leftStep;
rb[i].Top = topStep;
rb[i].Text = dt.Rows[i]["tachename"].ToString();
rb[i].CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
//
// label
//
l1[i] = new Label();
l1[i].AutoSize = true;
l1[i].Name = "lab" + i.ToString();
l1[i].Left = leftStep + 200;
l1[i].Top = topStep;
l1[i].Text = dt.Rows[i]["transactor"].ToString();
//添加到panel中去
this.content.Controls.Add(rb[i]);
this.content.Controls.Add(l1[i]);
topStep = topStep + 30;
}
//默认选中
rb[0].Checked = true;
topStep += 100;
//确定
Button ok = new Button();
ok.Top = topStep;
ok.Left = 120;
ok.Name = "ok";
ok.Height = 28;
ok.FlatStyle = FlatStyle.System;
ok.Text = "确定";
ok.Click += new EventHandler(btn_Click_1);
this.content.Controls.Add(ok);
//取消
Button cancel = new Button();
cancel.Top = topStep;
cancel.Left =ok.Width+150;
cancel.Name = "cancel";
cancel.Text = "取消";
cancel.Height = 28;
cancel.Click += new EventHandler(btn_Click_2);
this.content.Controls.Add(cancel);
}
}
注意循环里边的 选择事件绑定同一个radioButton_CheckedChanged方法里
rb[i].CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged);
运用委托进行选中
//全局变量
string backid="";
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
//选中的时候才执行,失去不执行...
if (((RadioButton)sender).Checked)
{
backid = ((RadioButton)sender).Name;
//MessageBox.Show(backid);//去掉if会弹出两次(上一个的失去,这一个的得到)
}
}
根据结果进行操作
public void btn_Click_2(object sender, System.EventArgs e)
{
MessageBox.Show(backid);
}
参考:
http://www.cnblogs.com/njnudt/archive/2007/07/30/835978.html
http://flydzk.blog.163.com/blog/static/982395322010188565455/