开发者

C# need to dynamically create radio buttons and determine which value user selected in Winform

开发者 https://www.devze.com 2023-01-09 21:41 出处:网络
I need to dynamically create radio开发者_Python百科 buttons based on dynamic list. Scenario is like I have list of files shown as Radio button in WinForm. A user clicks on radio button to select file

I need to dynamically create radio开发者_Python百科 buttons based on dynamic list. Scenario is like I have list of files shown as Radio button in WinForm. A user clicks on radio button to select file and move forward. I tried doing following as an example

for (int i = 0; i < 10; i++)  
{     
    ii = new RadioButton();  
    ii.Text = i.ToString();  
    ii.Location = new Point(20, tt);  
    tt = tt + 20;  
    panel1.Controls.Add(ii);                  
}

The problem is how would I check which value got selected by user?


A simple way to do it is by using the RadioButtons CheckChanged event to set a variable that specifies the file that they have chosen by using the RadioButtons text or Tag property which you could set to be the file itself?

e.g.

private File f = null;

for (int i = 0; i < 10; i++)
{
    ii = new RadioButton();
    ii.Text = i.ToString();
    ii.Location = new Point(20, tt);
    ii.Tag = fileArray[i]; // Assuming you have your files in an array or similar
    ii.CheckedChanged += new System.EventHandler(this.Radio_CheckedChanged);
    tt = tt + 20;
    panel1.Controls.Add(ii);
}

private void Radio_CheckedChanged(object sender, EventArgs e)
{
    RadioButton r = (RadioButton)sender;
    f = (File)r.Tag;
}

It's certainly not the most elegant way but it would work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号