winform动态创建radio以及使用委托判断哪个选中

创建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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值