0

How to reference checkbox by name (string), in C# Windows Forms? I am trying

CheckBox cb = (CheckBox)Controls["checkBox" + id];
if (cb.Checked)
{
    MessageBox.Show(id);
}

I am getting

Error   2   Cannot convert type 'System.Windows.Forms.Control' to 'Vts_SI.CheckBox' C:\Users\Administrator\Documents\Visual Studio 2010\Projects\My2\My2\GlavniProzor.cs    67  27  Vts_SI
Error   3   'Vts_SI.CheckBox' does not contain a definition for 'Checked' and no extension method 'Checked' accepting a first argument of type 'Vts_SI.CheckBox' could be found (are you missing a using directive or an assembly reference?)   C:\Users\Administrator\Documents\Visual Studio 2010\Projects\My2\My2\GlavniProzor.cs    68  20  Vts_SI
7
  • 1
    Provide the exact error you get. and also is this compile time error or runtime Exception ? Commented Jan 18, 2014 at 17:33
  • Error occurs in design time. Updated full error list response. Commented Jan 18, 2014 at 17:42
  • User K.B has a answer for you That's what you need Commented Jan 18, 2014 at 17:43
  • The actual problem is that there is no .Checked function available for that control, you should take a look at the documentation. Commented Jan 18, 2014 at 17:45
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Jan 18, 2014 at 17:50

4 Answers 4

4

You may have a class with the some name CheckBox you should specify explicitly the name space

System.Windows.Forms.CheckBox cb
    = (System.Windows.Forms.CheckBox)Controls["checkBox" + id];
Sign up to request clarification or add additional context in comments.

4 Comments

+1 and finally we got the winner, I was waiting for OP to confirm this is a compile time error.
Typing variable is not enough I suppose, you may need the same in cast also:)
This still gives Error 2 Cannot convert type 'System.Windows.Forms.Control' to 'Vts_SI.CheckBox' - What am I missing?
@SlinavaSurla take a look I updated my answer what is missing is the namespace even in the cast
1

Use this:

public T Control<T>(String id) where T : Control
{
   foreach (Control ctrl in MainForm.Controls.Find(id, true))
   {
      return (T)ctrl; // Form Controls have unique names, so no more iterations needed
   }
   throw new Exception("Control not found!");
}

1 Comment

This doesn't make any sense. For example, why use foreach to do at most one iteration?
0

Controls.Add(dynamicCheckBox);

Why don't you try Dynamic checkbox instead.

system.Windows.Forms.dynamiccheckBox cb1 = (dynamiccheckBox)Controls["dynamiccheckBox" + id];

Comments

-3

Type: System.Windows.Forms.CheckState One of the CheckState enumeration values. The default value is Unchecked. Try this but a bit lengthy

using System;
using System.Windows.Forms;

namespace DynamicCheckBoxes
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            // Create example Form (normally you would create it with the VS Forms Designer)
            Form form = new Form();

        // Use a Panel to add the CheckBoxes during runtime
        Panel panel = new Panel();
        panel.Dock = DockStyle.Fill;
        panel.Parent = form;

        // Add a button to the form for creating the CheckBoxes during runtime
        Button button = new Button();
        button.Text = "Add a new CheckBox";
        button.Dock = DockStyle.Bottom;
        button.Parent = form;

        // On Button.Click we add a new CheckBox - we use a inline delegate here
        // Remark: Notice how the "outer" scope variables are captured.
        int iCount = 0;
        button.Click += delegate(object sender, EventArgs e)
        {
            iCount++;
            CreateCheckbox("cbDynamic" + iCount, "Dynamic" + iCount, panel, SampleCheckChangedHandler);
        }; 

        // Now let's create some Checkboxes in code 
        // I created a helper function to do the job.
        CreateCheckbox("cbActs", "Acts", panel, SampleCheckChangedHandler);
        CreateCheckbox("cbLaw", "Law", panel, SampleCheckChangedHandler);
        CreateCheckbox("cbHouses", "Houses", panel, SampleCheckChangedHandler);
        CreateCheckbox("cbCar", "Car", panel, SampleCheckChangedHandler);           

        Application.Run(form);
    }

    /// <summary>
    /// Helper function to create a CheckBox with common properties and adding it to the given parent control.
    /// </summary>
    /// <param name="Name"> Name for the new CheckBox </param>
    /// <param name="Text"> Text of the new CheckBox </param>
    /// <param name="ctrlParent"> Parent control for the new CheckBox (can be null if parent is set through other logic later) </param>
    /// <param name="handlerCheckChanged"> Handler for the CheckChanged event (can be null if no handler is needed) </param>
    /// <returns> The new Checkbox </returns>
    static CheckBox CreateCheckbox(string strName, string strText, Control ctrlParent, EventHandler handlerCheckChanged)
    {
        CheckBox cb = new CheckBox();
        cb.Name = strName;
        cb.Text = strText;
        cb.Dock = DockStyle.Top; // give a thought on how to do the dynamic layout,
        // maybe use a container control..
        cb.Parent = ctrlParent; // same as ctrlParent.Controls.Add(cb)
        // add some EventHandler (use this code as template if other handlers are commonly needded,
        // but add/set handlers/properties for specific CheckBoxes created with this function to the 
        // returned CheckBox object
        cb.CheckedChanged += handlerCheckChanged;

        return cb;
    }

    /// <summary>
    /// Sample eventhandler for the CheckChanged event
    /// </summary>
    static void SampleCheckChangedHandler(object objSender, EventArgs ea)
    {
        CheckBox cb = objSender as CheckBox; // get a reference to the checked/unchecked CheckBox

        // Do something just for demo
        if (cb.Checked)
            MessageBox.Show(cb.Text + " checked");
        else
            MessageBox.Show(cb.Text + " unchecked");
    }
}

}

2 Comments

I'm not wasting my rep downvoting this.
@puretppc Better idea! you can flag it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.