I have some user controls that do not support RightToLeft Layout and I have the DLLs only.
I want implement RightToLeft Layout in these controls by code.
How can I do that?
Note : I try to use TableLayoutPanel and FlowLayoutPanel, but the problem still exists.
You have to do it manually using some logic.
private bool isLeft = true;
private void SwapPosition()
{
isLeft = !isLeft;
foreach (Control cnt in this.Controls)
SwapPosition(cnt);
}
private void SwapPosition(Control cnt)
{
cnt.Left = cnt.Parent.Width - (cnt.Left + cnt.Width);
///Assign other properties also
///ie. cnt.RightToLeft = !isLeft
///if (isLeft) then NormalFont else Hebrew or any
foreach (Controls cntChild in cnt.Controls)
RightToLeft(cntChild);
}
Related
I have many buttons and labels on my c# form. I have a button that changes all butons' and labels' text properties (change language button). Do i have to write all items in click event of button or is there a method that scans all form control items and change their text properties.
There are many other controls that contains labels or buttons. For example a label is added to the control of a panel and when i iterate form controls, i can't reach this label. I want to change all items' text properties at one time.
Thank you.
foreach (Control objCtrl in yourFormName.Controls) {
if (objCtrl is Label)
{
// Assign Some Text
}
if (objCtrl is Button)
{
// Assign some text
}
}
If a CS0120 error happens, change yourFormName.Controls to this.Controls;
Assuming ASP.NET's ITextControl Interface (works similar for Winforms-Controls' Text-Property ):
var text = "Hello World";
var allTextControls = this.Controls.OfType<ITextControl>();
foreach(ITextControl txt in allTextControls)
txt.Text = text;
http://msdn.microsoft.com/en-us/library/bb360913.aspx
Edit: You could easily make it an extension(e.g. ASP.NET, for Winforms replace ITextControl with Control):
public static class ControlExtensions
{
public static void SetControlChildText(this Control rootControl, String text, bool recursive)
{
var allChildTextControls = rootControl.Controls.OfType<ITextControl>();
foreach (ITextControl txt in allChildTextControls)
txt.Text = text;
if (recursive) {
foreach (Control child in rootControl.Controls)
child.SetControlChildText(text, true);
}
}
}
Now you can call it for example in this way:
protected void Page_Load(object sender, EventArgs e)
{
Page.SetControlChildText("Hello World", true);
}
This will apply the given text on every child control implementing ITextControl(like Label or TextBox).
If it's winforms you should read about localizing your application here:
Walkthrough: Localizing Windows Forms
I think if you are using javascript, you can simply go through the DOM and modify the texts of the buttons and labels. Using jQuery this will be very simple
For a web application, you could do this quite easily with jQuery. Have a look at this: http://api.jquery.com/category/selectors/
$('label').each(function(){this.value = 'something else';});
For Winforms, you can use this:
foreach (var c in Controls.OfType<TextBox>())
c.Text = "TextBox Text";
foreach (var c in Controls.OfType<Label>())
c.Text = "Label text";
But I agree with #ionden, you should consider localizing your application.
There is a Controls property that contains all controls of your form. You can iterate over it:
foreach(var control in Controls)
{
var button = control as Button;
if(button != null)
button.Text = Translate(button.Text);
else
{
var label = control as Label;
if(label != null)
label .Text = Translate(label .Text);
}
}
foreach( Control ctlparent in this.Controls)
{
if(ctlparent is Panel or ctlparent is GroupBox)
{
foreach(Control ctl in ctlparent.Controls)
{
if(ctl is Label or ctl is Button)
{
ctl.Text= newtext;
}
}}
This will work.
I have groupbox I want to clear all the control in it , I try
public void ClearPanels(GroupBox control)
{
foreach (Control p in control.Controls)
{
control.Controls.Remove(p);
}
}
but a panel remain it , the problem I create the controls in runtime , and want to remove it in runtime
Better use this which clears all the controls at once without using a loop:
public void ClearPanels(GroupBox control)
{
control.Controls.Clear();
}
Use RemoteAt
while (control.Controls.Count > 0)
{
control.Controls.RemoveAt(0);
}
or Clear
control.Controls.Clear();
What is the best way to dynamically modify the forecolor and background color of every control of a WinForm application consisting of buttons, toolstrips, panels, etc? Is there an easy way to cycle through each control automatically or do I have to manually change each one? Thanks.
You can cycle through controls, I believe that all controls have a Controls property that is a list of contained controls.
Hypothetical function:
public void ChangeControlsColours(Controls in_c)
{
foreach (Control c in in_c)
{
c.BackColor = Colors.Black;
c.ForeColor = Colors.White;
if (c.Controls.length >0 ) //I'm not 100% this line is correct, but I think you get the idea, yes?
ChangeControlsColours(c.Controls)
}
}
foreach (Control c in MyForm.Controls) {
c.BackColor = Colors.Black;
c.ForeColor = Colors.White;
}
It really depends on what you're trying to do. The most elegant way might be a linked application setting you define on design time and you're then be able to change on run time.
private void UpdateInternalControls(Control parent)
{
UpdateControl(parent, delegate(Control control)
{
control.BackColor = Color.Turquoise;
control.ForeColor = Color.Yellow;
});
}
private static void UpdateControl(Control c, Action<Control> action)
{
action(c);
foreach (Control child in c.Controls)
{
UpdateControl(child, action);
}
}
I'm trying to get all controls in a winform disabled at the Load event.
I have a form (MDI) which loads a Login Form. I want to disable the controls behind the Login Form to only let the user enter his username and password, and then if the user is valid re-enable the controls again.
Just show the login form as a modal dialog, i.e., frm.ShowDialog( ).
Or, if you really want to disable each control, use the Form's Controls collection:
void ChangeEnabled( bool enabled )
{
foreach ( Control c in this.Controls )
{
c.Enabled = enabled;
}
}
I suggest doing it this way instead of simply setting the Form's Enabled propery because if you disable the form itself you also disable the tool bar buttons. If that is ok with you then just set the form to disabled:
this.Enabled = false;
However, if you are going to do this you may as well just show the login prompt as a modal dialog :)
Simple Lambda Solution
form.Controls.Cast<Control>()
.ToList()
.ForEach(x=>x.Enabled = false);
Container like Panel control that contains other controls
then I used queue and recursive function get all controls.
for (Control control in GetAllControls(this.Controls))
{
control.Enabled = false;
}
public List<Control> GetAllControls(Control.ControlCollection containerControls, params Control[] excludeControlList)
{
List<Control> controlList = new List<Control>();
Queue<Control.ControlCollection> queue = new Queue<Control.ControlCollection>();
queue.Enqueue(containerControls);
while (queue.Count > 0)
{
Control.ControlCollection controls = queue.Dequeue();
if (controls == null || controls.Count == 0)
continue;
foreach (Control control in controls)
{
if (excludeControlList != null)
{
if (excludeControlList.SingleOrDefault(expControl => (control == expControl)) != null)
continue;
}
controlList.Add(control);
queue.Enqueue(control.Controls);
}
}
return controlList;
}
Just for some fun with linq, because you can.....
What you could do is create a "BatchExecute" extension method for IEnumerable and update all your controls in 1 hit.
public static class BatchExecuteExtension
{
public static void BatchExecute<T>(this IEnumerable<T> list, Action<T> action)
{
foreach (T obj in list)
{
action(obj);
}
}
}
Then in your code....
this.Controls.Cast<Control>().BatchExecute( c => c.enabled = false);
Cool.
I agree that ShowDialog is the way to go, but to answer the original question, you can do this if you want to disable all controls:
foreach (Control c in this.Controls)
{
c.Enabled = false;
}
As Ed said, showing the form as a modal dialog will do what you want. Be sure to check the dialog result returned from ShowDialog in case they cancel it instead of clicking login.
But if you really want to disable all the controls on the form then you should be able to just disable the form itself, or some other parent control like a panel that has all controls in it. That will disable all child controls. This will also allow the child controls to go back to their previous state when the parent control is enabled again.
Trying the ShowDialog show this exception:
Form that is not a top-level form cannot be displayed as a modal dialog box. Remove the form from any parent form before calling showDialog.
What im doing is this:
private void frmControlPanel_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
ShowLogin();
//User = "GutierrezDev"; // Get user name.
//tssObject02.Text = User;
}
private void ShowLogin()
{
Login = new frmLogin
{
MdiParent = this,
Text = "Login",
MaximizeBox = false,
MinimizeBox = false,
FormBorderStyle = FormBorderStyle.FixedDialog,
StartPosition = FormStartPosition.CenterScreen
};
Login.ShowDialog();
}
I have multiple dropdownlist in a page and would like to disable all if user selects a checkbox which reads disable all. So far I have this code and it is not working. Any suggestions?
foreach (Control c in this.Page.Controls)
{
if (c is DropDownList)
((DropDownList)(c)).Enabled = false;
}
Each control has child controls, so you'd need to use recursion to reach them all:
protected void DisableControls(Control parent, bool State) {
foreach(Control c in parent.Controls) {
if (c is DropDownList) {
((DropDownList)(c)).Enabled = State;
}
DisableControls(c, State);
}
}
Then call it like so:
protected void Event_Name(...) {
DisableControls(Page,false); // use whatever top-most control has all the dropdowns or just the page control
} // divs, tables etc. can be called through adding runat="server" property
I know this is an old post but this is how I have just solved this problem. AS per the title "How do I disable all controls in ASP.NET page?" I used Reflection to achieve this; it will work on all control types which have an Enabled property. Simply call DisableControls passing in the parent control (I.e., Form).
C#:
private void DisableControls(System.Web.UI.Control control)
{
foreach (System.Web.UI.Control c in control.Controls)
{
// Get the Enabled property by reflection.
Type type = c.GetType();
PropertyInfo prop = type.GetProperty("Enabled");
// Set it to False to disable the control.
if (prop != null)
{
prop.SetValue(c, false, null);
}
// Recurse into child controls.
if (c.Controls.Count > 0)
{
this.DisableControls(c);
}
}
}
VB:
Private Sub DisableControls(control As System.Web.UI.Control)
For Each c As System.Web.UI.Control In control.Controls
' Get the Enabled property by reflection.
Dim type As Type = c.GetType
Dim prop As PropertyInfo = type.GetProperty("Enabled")
' Set it to False to disable the control.
If Not prop Is Nothing Then
prop.SetValue(c, False, Nothing)
End If
' Recurse into child controls.
If c.Controls.Count > 0 Then
Me.DisableControls(c)
End If
Next
End Sub
It would be easiest if you put all the controls you want to disable in a panel and then just enable/disable the panel.
Put a panel around the part of the page that you want disabled:
< asp:Panel ID="pnlPage" runat="server" >
...
< /asp:Panel >
Inside of Page_Load:
If Not Me.Page.IsPostBack Then
Me.pnlPage.Enabled = False
End If
... or the C# equivalent. :o)
You have to do this recursive, I mean you have to disable child controls of controls to :
protected void Page_Load(object sender, EventArgs e)
{
DisableChilds(this.Page);
}
private void DisableChilds(Control ctrl)
{
foreach (Control c in ctrl.Controls)
{
DisableChilds(c);
if (c is DropDownList)
{
((DropDownList)(c)).Enabled = false;
}
}
}
I was working with ASP.Net and HTML controls I did like this
public void DisableForm(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Enabled = false;
if (ctrl is Button)
((Button)ctrl).Enabled = false;
else if (ctrl is DropDownList)
((DropDownList)ctrl).Enabled = false;
else if (ctrl is CheckBox)
((CheckBox)ctrl).Enabled = false;
else if (ctrl is RadioButton)
((RadioButton)ctrl).Enabled = false;
else if (ctrl is HtmlInputButton)
((HtmlInputButton)ctrl).Disabled = true;
else if (ctrl is HtmlInputText)
((HtmlInputText)ctrl).Disabled = true;
else if (ctrl is HtmlSelect)
((HtmlSelect)ctrl).Disabled = true;
else if (ctrl is HtmlInputCheckBox)
((HtmlInputCheckBox)ctrl).Disabled = true;
else if (ctrl is HtmlInputRadioButton)
((HtmlInputRadioButton)ctrl).Disabled = true;
DisableForm(ctrl.Controls);
}
}
called like this
DisableForm(Page.Controls);
Here's a VB.NET version which also takes an optional parameter so it can be used for enabling the controls as well.
Private Sub SetControls(ByVal parentControl As Control, Optional ByVal enable As Boolean = False)
For Each c As Control In parentControl.Controls
If TypeOf (c) Is CheckBox Then
CType(c, CheckBox).Enabled = enable
ElseIf TypeOf (c) Is RadioButtonList Then
CType(c, RadioButtonList).Enabled = enable
End If
SetControls(c)
Next
End Sub
private void ControlStateSwitch(bool state)
{
foreach (var x in from Control c in Page.Controls from Control x in c.Controls select x)
if (ctrl is ASPxTextBox)
((ASPxTextBox)x).Enabled = status;
else if (x is ASPxDateEdit)
((ASPxDateEdit)x).Enabled = status;
}
I use a linq aproach. While using devExpress you must include
DevExpress.Web.ASPxEditors lib.
If you really want to disable all controls on a page, then the easiest way to do this is to set the form's Disabled property to true.
ASPX:
<body>
<form id="form1" runat="server">
...
</form>
</body>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
form1.Disabled = true;
}
But of course, this will also disable your checkbox, so you won't be able to click the checkbox to re-enable the controls.