Just learning C#, radiobuttons and checkboxes. No urgency.
The code works to display the names of the checked controls but it doesn’t seem to be an elegant solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TVC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "you clicked" + compute();
}
string compute()
{
string result = "";
object o=label1;
while (((Control)o).TabIndex!=7)
{
if ((o is RadioButton)||(o is CheckBox))
{
if ((o is RadioButton)&&((RadioButton)o).Checked)
result += " "+((RadioButton)o).Text;
if ((o is CheckBox)&&((CheckBox)o).Checked)
result += " "+((CheckBox)o).Text;
}
o = GetNextControl((Control)o, true);
}
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
The checboxes and radiobuttons tabindexes are counted from 1to 6, the label is 0 and the button is 7 so that GetNextControl works. Is there a nicer code that would work ?
I just tested this and verified that it works. It uses recursion and the newer
dynamickeyword as it appears thatRadioButtonandCheckBoxinherit fromButtonBase, which does not have theCheckedproperty, otherwise you could cast down to that. The dynamic allows me to avoid that since I already know the control types.