I have a GroupBox
control in my Windows Forms application, inside of which I have placed some TextBox
controls. How can I disable the GroupBox
control while making the individual TextBox
controls read-only?
Whenever I disable the GroupBox
, all of the TextBox
c开发者_StackOverflowontrols inside of it get disabled as well. I can't figure out how to make them read-only.
When you disable a container control (such as a GroupBox
), all of its children become disabled as well. That's just how it works in Windows; it's not possible to change that behavior.
Instead, you need to set the ReadOnly
property of each individual TextBox
control to true. If you disable the entire GroupBox
, each TextBox
control it contains will be disabled as well, which overrides the state of the ReadOnly
property and prevents the user from copying its contents.
Once you've fixed the section of your code that disables the GroupBox
, you can use a simple foreach
loop to do the dirty work of setting the property on each TextBox
control:
foreach (TextBox txt in myGroupBox.Controls)
{
txt.ReadOnly = true;
}
This will make all the textboxes in the groupbox readonly.
foreach(TextBox t in groupBox1.Controls)
{
t.ReadOnly = true;
}
Actually, if you set the Enabled property of a groupbox to false. All contents in it (textbox, etc.) will become disabled too. But you can still do it using:
foreach (Control ctrl in groupBox1.Controls)
{
if (ctrl is TextBox)
{
((TextBox)ctrl).ReadOnly = true;
}
}
I think what you mean here is that you want to disable the groupbox and at the same time - don't want the textboxes to be shown as grayed... If this is something you want to achieve, you better put these textboxes in Panel and then set them ReadOnly as you would do for any control.
精彩评论