Question

I have a form on which are "listBox1" and "button1". I have two function. The second function adds checkboxes to listbox1 and the first function displays message box. But I don´t know how to write the first function.

Here I want to check which checkbox is checked and write a message:

private void button1_click(object sender, EventArgs e)
{
    MessageBox.Show("radiobutton: " + rb[i].Text);
}

Here I create checkboxes: //it´s working

internal void loadSurveys()
{
    WebClient client2 = new WebClient();
    var json = client2.DownloadString("http://www.test.net/api/surveys/?api_key=123");
    JObject data = JObject.Parse(json);
    var example = JsonConvert.DeserializeObject<Example>(json);
    int y = 5;
    int i = 0;
    RadioButton[] rb = new RadioButton[example.surveys.Length];
    String chkBox_name = "";
    String chkBox_text = "";
    foreach (var survey in data["surveys"].Children())
    {
        rb[i] = new RadioButton();
        rb[i].Location = new Point(5, y);
        rb[i].Name = chkBox_name + survey["id"];
        rb[i].Text = chkBox_text + survey["title"];
        rb[i].AutoSize = true;
        this.listBox1.Controls.Add(rb[i]);
        y += 20;
        i++;
    }

}
Was it helpful?

Solution

You can go through listBox1.Controls and pick checked RadioButton

private void button1_click(object sender, EventArgs e)
{
    var rb = this.listBox1.Controls.OfType<RadioButton>().SingleOrDefault(n => n.Checked);
    if (rb != null)
        MessageBox.Show("radiobutton: " + rb.Text);
}

since this is RadioButton there shouldn't be more then one checked

OTHER TIPS

The first step, is to make the radiobutton array a variable on form level:

RadioButton[] rb

which is assigned inside loadSurveys

rb = new RadioButton[example.surveys.Length];

Then the array is accessible inside your button click

var rb = rb.FirstOrDefault(r=>r.Checked);
if(rb==null)
    MessageBox.Show("No radiobutton was selected");
else
    MessageBox.Show("radiobutton: " + rb[i].Text);

edit Just noticed you add the radiobuttons to a listbox. Is the listbox1 variable an actual listbox? The above will still work, but if the goal is to display a listbox of radiobuttons, you can custom paint the listbox and else use a normal panel instead of a listbox. Either way, you can also do a firstordefault on the controls on the controls of the listbox1 variable (with OfType), but if you'd use a listbox, and fill its items, you could simply use SelectedIndexChanged

edit 2 Since I already had it, wanted to show a way to make your listbox a radiobutton box. You can make any existing listbox a radiobutton box with the following class:

public class RadioButtonBoxPainter:IDisposable
{

    public readonly ListBox ListBox;
    public RadioButtonBoxPainter(ListBox ListBox)
    {
        this.ListBox = ListBox;
        ListBox.DrawMode = DrawMode.OwnerDrawFixed;
        ListBox.DrawItem += ListBox_DrawItem;
    }

    void ListBox_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index == -1) return;
        Rectangle r = e.Bounds;
        r.Width=r.Height;
        bool selected= (e.State & DrawItemState.Selected) > 0;
        e.DrawBackground();
        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        ControlPaint.DrawRadioButton(e.Graphics, r, selected ? ButtonState.Checked : ButtonState.Normal);
        r.X = r.Right + 2;
        r.Width = e.Bounds.Width - r.X;
        string txt;
        if (ListBox.Site != null && ListBox.Site.DesignMode && e.Index >= ListBox.Items.Count)
            txt = ListBox.Name;
        else
            txt = ListBox.GetItemText(ListBox.Items[e.Index]);
        using (var b = new SolidBrush(e.ForeColor))
            e.Graphics.DrawString(txt, e.Font, b, r);
        if (selected)
        {
            r = e.Bounds;
            r.Width--; r.Height--;
            e.Graphics.DrawRectangle(Pens.DarkBlue, r);
        }
    }

    public void Dispose()
    {
        ListBox.DrawItem -= ListBox_DrawItem;
    }
}

Example of a standard implementation:

public class RadioButtonBox:ListBox
{
    public readonly RadioButtonBoxPainter Painter;

    public RadioButtonBox()
    {
        Painter = new RadioButtonBoxPainter(this);
    }

    [DefaultValue(DrawMode.OwnerDrawFixed)]
    public override DrawMode DrawMode
    {
        get{return base.DrawMode;}
        set{base.DrawMode = value;}
    }
}

The RadioButtonBox is a control I actually use a lot. Personally I find it a lot quicker in implementing then a load of separate radiobuttons.

In case you want to use it, and want an example how to implement it in your current code, leave a comment and I'll add one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top