开发者

C# user controls

How to add controls in parent control I am using C# windows application

I have a user control including group box and checkbox group box, controls gets enabled or disabled on the basis开发者_如何学运维 of checked property of check box now when using this control in other application how can i add controls in group box?? so that they can get enabled o disabled in my application


Do you want to add controls via code (programatically) or using the designer?

If you want to add a control to a groupbox, panel, or other container, first you create the control:

Label myLabel = new Label();
myLabel.Name = "Name";
myLabel.Text = "Example";
myLabel.Location = new Point(10, 10);

Then, add it to the container using the container's Controls property, via the add method:

myGroupBox.Controls.Add(myLabel);

Finally, you can use the state of your checkbox to enable/disable the entire container (and all its child controls). You may want to use a boolean somewhere, but this is the basic idea:

In the CheckChanged event for your Checkbox, do this:

myGroupBox.Enabled = myCheckBox.Checked;

Or the inverse, depending on how you want the enabled state.

EDIT:

From your comment, it sounds like you want to add additional controls to an existing user control after design time. You would need to provide that functionality in a public method.

public void AddControl(Control controlToAdd)
{
    myGroupBox.Controls.Add(controlToAdd);
}

Basically exposing the user control container's Controls.Add to the code which interacts with your user control.

I hope this is helpful.

EDIT 2:

Here is the code you posted in a comment:

foreach(Control ctrl in this.groupbox1.Controls)
{
    if (ctrl != this.checkbox1)
    {
        ctrl.Enabled = this.checkbox1.Checked;
    }
}

This iterates through all the controls, and enables or disables all of them except checkbox1 based on checkbox1's checked state.

First, if checkbox1 is not a child control in groupbox1, there's no need for the if statement that ensures the current control is not checkbox1. It never will be, because the foreach is only iterating the child controls of groupbox1. As long as checkbox1 is outside of groupbox1, it is omitted from the iteration.

Second, it is much quicker and easier to maintain if you simply enable or disable the entire groupbox. All controls within it will inherit the enabled/disabled state. Using your control names the code would be:

groupbox1.Enabled = checkbox1.Checked;

I hope I am understanding your question correctly.


I ended up making an user control, in which I added a group box inside the check box. So the group box is enabled and disable based on the check box.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜