How to set IsEnabled false to all buttons of radiobutton - c#

I am c# developer and i am trying programatically to set all the radiobutton to false.
How to set all the radiobutton to IsEnabled= false ?
EDIT:Please note that i have kind of situation where i have to keep this radio.IsEnabled = false; outside the loop only so is there any way that i still can have all button IsEnable= false ?

try below code and take isEnable inside the block of code as shown below
foreach (String item in param.Component.Attributes[0].Item)
{
radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
// Name = "param_"+param.Name
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
};
sp.Children.Add(radio);
radio.IsEnabled = false;
count++;
}

You are using variable radio declared outside the function, declare it as local variable like this, and set IsEnabled each time you create it:
foreach (String item in param.Component.Attributes[0].Item)
{
RadioButton radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
// Name = "param_"+param.Name
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
};
radio.IsEnabled = false;
sp.Children.Add(radio);
count++;
}

Thats because you put the radio.IsEnabled = false; outside of the loop.
{
radio = new RadioButton()
{
Content = item,
GroupName = "MyRadioButtonGroup",
// Name = "param_"+param.Name
};
radio.Checked += (o, e) =>
{
txtblkShowStatus.Text = item;
};
sp.Children.Add(radio);
radio.IsEnabled = false;
count++;
}

I assume putting radio.IsEnabled = false; inside your loop will do the trick..
EDIT :
I am not sure I quite understand why you want to set to false in second step however you can try:
foreach (Radiobutton r in sp.Childern)
{
r.IsEnabled = false;
}

Related

ObjectListView - Rows are formatted only after MouseOver on Items

I am in need of some assistance or advice/experience of someone else.
Here is what I'm struggling with:
In my project an objectlistview olvDifference is used to visualize items (Type Conflict) of a list. So far I was able to add the Columns needed and format them properly. But the format provided with
private void ConflictFormatRow(object sender,
BrightIdeasSoftware.FormatRowEventArgs e)
{
Conflict conflict = (Conflict)e.Model;
if (conflict == null) return;
if (conflict.resolution == ConflictResolution.None) e.Item.BackColor = conflictColor;
else if (conflict.resolution == ConflictResolution.UseMine) e.Item.BackColor = mineColor;
else if (conflict.resolution == ConflictResolution.UseTheirs) e.Item.BackColor = theirsColor;
else e.Item.BackColor = System.Drawing.Color.White;
if(e.Model == olvConflictList.SelectedObject)
{
BrightIdeasSoftware.RowBorderDecoration a = new BrightIdeasSoftware.RowBorderDecoration();
a.BorderPen.Color = Color.Black;
a.BorderPen.Width = 3;
a.CornerRounding = 0;
a.FillBrush = Brushes.Transparent;
e.Item.Decoration = a;
}
else
{
BrightIdeasSoftware.RowBorderDecoration b = new BrightIdeasSoftware.RowBorderDecoration();
b.BorderPen.Color = Color.Transparent;
b.BorderPen.Width = 0;
b.CornerRounding = 0;
b.FillBrush = Brushes.Transparent;
e.Item.Decoration = b;
}
}
In the constructor of the form (WFA), the AspectGetter is assigned and the objects to display are set.
Designer-Generated code equals the block below:
//
// olvConflictList
//
this.olvConflictList.AllColumns.Add(this.olvcConflictList);
this.olvConflictList.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.olvConflictList.CellEditUseWholeCell = false;
this.olvConflictList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvcConflictList});
this.olvConflictList.Cursor = System.Windows.Forms.Cursors.Default;
this.olvConflictList.FullRowSelect = true;
this.olvConflictList.Location = new System.Drawing.Point(780, 90);
this.olvConflictList.Name = "olvConflictList";
this.olvConflictList.Size = new System.Drawing.Size(286, 489);
this.olvConflictList.TabIndex = 18;
this.olvConflictList.UseCellFormatEvents = true;
this.olvConflictList.UseCompatibleStateImageBehavior = false;
this.olvConflictList.View = System.Windows.Forms.View.Details;
this.olvConflictList.FormatRow += new System.EventHandler<BrightIdeasSoftware.FormatRowEventArgs>(this.ConflictFormatRow);
this.olvConflictList.SelectedIndexChanged += new System.EventHandler(this.olvDifferenceGroups_SelectedIndexChanged);
//
// olvcConflictList
//
this.olvcConflictList.AspectName = "";
this.olvcConflictList.AutoCompleteEditor = false;
this.olvcConflictList.AutoCompleteEditorMode = System.Windows.Forms.AutoCompleteMode.None;
this.olvcConflictList.FillsFreeSpace = true;
this.olvcConflictList.Groupable = false;
this.olvcConflictList.HeaderCheckBoxUpdatesRowCheckBoxes = false;
this.olvcConflictList.Hideable = false;
this.olvcConflictList.IsEditable = false;
this.olvcConflictList.MinimumWidth = 50;
this.olvcConflictList.Searchable = false;
this.olvcConflictList.Sortable = false;
this.olvcConflictList.Text = "Conflicts";
this.olvcConflictList.UseFiltering = false;
this.olvcConflictList.Width = 283;
The only item in the olv has no BackGroundColor (White, default):
After starting the process, it is shown as one can see in the pic above, but I'd expect it to be initialized as in the pic below (after I hovered over it with my mouse the first time).
The only item in the olv has BackGroundColor conflictColor as assigned in the ConflictFormatRow:
Where do I need to improve my code? Any advices?
Well, I could figure it out myself.
I took a look at the source of OLV and what i found out so far:
In my case, the first row, here "Conflicts", was set to "Groupable=False", but the OLV itself was set to "ShowGroups=True".
FormatRow is fired in PostProcessOneRow, which is called according to source (Version: 2.9.1.0) in following logic:
protected virtual void PostProcessRows() {
// If this method is called during a BeginUpdate/EndUpdate pair, changes to the
// Items collection are cached. Getting the Count flushes that cache.
#pragma warning disable 168
// ReSharper disable once UnusedVariable
int count = this.Items.Count;
#pragma warning restore 168
int i = 0;
if (this.ShowGroups) {
foreach (ListViewGroup group in this.Groups) {
foreach (OLVListItem olvi in group.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
} else {
foreach (OLVListItem olvi in this.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
}
Since grouping failed, due to no groupable rows being present in OLV, the PostProcessOneRow in the if-body was not hit even once (foreach operated in "this.Groups" whichs count was 0).
Set "ShowGroups=False", works like a charm now.

Turn textboxes and buttons visible when the number of tracks it's selected in a combobox

I'm trying to turn textboxes and buttons visible when the number of tracks it's selected in a combobox.
For example: when I select 3, just 3 textboxes and the 3 respective buttons to select the tracks are enabled. How can I change this code that I've made to a simple foreach or a for?
if (numero_faixas == 1) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
} else if (numero_faixas == 2) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
} else if (numero_faixas == 3) {
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
You can reduce the lines of code by changing your conditions, so you don't have to reference the same control so many times:
if (numero_faixas > 0)
{
txtFaixa1.Visible = true;
btnFaixa1.Visible = true;
}
if (numero_faixas > 1)
{
txtFaixa2.Visible = true;
btnFaixa2.Visible = true;
}
if (numero_faixas > 2)
{
txtFaixa3.Visible = true;
btnFaixa3.Visible = true;
}
To use a foreach loop, you could cast the Controls collection to an IEnumerable<Control> and then, using System.Linq;, you can filter on controls of type TextBox and Button, where the control name contains "Faxia". Then, in the loop body, we can use int.TryParse to try to convert the last character of the control name to an int, and if that succeeds, then set the control to Visible if the control number is less than numero_faixas + 1:
foreach (Control control in Controls.Cast<Control>()
.Where(c => (c is Button || c is TextBox) && c.Name.Contains("Faixa")))
{
// Get the number associated with this control and compare it to numero_faixas
int controlNumber;
if (int.TryParse(control.Name.Substring(control.Name.Length - 1), out controlNumber) &&
controlNumber < numero_faixas + 1)
{
control.Visible = true;
}
}
Here's a proof of concept that you could respin using your business rules.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ShowHideButtons_47439046
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitOurThings();
}
private void InitOurThings()
{
//lets create a combo box with options to select
ComboBox combo = new ComboBox();
combo.Location = new Point(5, 5);//place it somewhere
//add selectable items
for (int i = 0; i < 10; i++)
{
combo.Items.Add(i);
}
combo.SelectedValueChanged += Combo_SelectedValueChanged;//the event which will handle the showing/hidding
Controls.Add(combo);//add the combo box to the form
//lets create some buttons and textboxes
int btnx = 5;
int btny = combo.Height + combo.Location.Y + 5;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Location = new Point(btnx, btny);
btn.Name = i.ToString();
btn.Text = i.ToString();
Controls.Add(btn);
btny += btn.Height + 5;
TextBox txtbx = new TextBox();
txtbx.Location = new Point(btn.Location.X + btn.Width + 5, btn.Location.Y);
txtbx.Name = i.ToString();
txtbx.Text = i.ToString();
Controls.Add(txtbx);
}
}
private void Combo_SelectedValueChanged(object sender, EventArgs e)
{
int selectedValue = int.Parse(((ComboBox)sender).SelectedItem.ToString());
foreach (Control item in Controls)
{
//show/hide the controls based on their Name being Equal Or Smaller than the selectedItem
if (item is TextBox)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
if (item is Button)
{
int itemNumber = int.Parse(item.Name);
item.Visible = itemNumber <= selectedValue ? true : false;
}
}
}
}
}

Get control of Radio Button

I have radio buttons, around 200, whose ID are KP1, KP2, KP3... KP200. I would like to run a for loop to check if they are checked or not.
I get a crash at the line no 9:
RbId = CtrlId;
I would like to extract the Radio Button Ctrl from the string similar to how it's done using javascript ie.,
document.getElementById("<%=ID%>").
Please advise.
Code:
int i;
RadioButton RbId = null;
string CtrlId = null;
char[] KPList = new char[200];
for (i = 1; i <= 200; i++)
{
CtrlId = "KP"+i.ToString();
RbId = CtrlId;
if(RbId.Checked)
{
KPList[i] = (char)j;
break;
}
}
You can use FindControl() method in for it:
Control ctrl = this.FindControl(CtrlId);
if (ctl is RadioButton)
{
RadioButton rdBtn = ctrl as RadioButton;
// now do whatever here
if(rdBtn.Checked)
{
}
}
Try this:
foreach (RadioButton rdbtn in myDiv.Controls.OfType<RadioButton>())//Assume the RadioButtons are inside a div tag called myDiv
{
if(rdbtn.Checked)
{
....
}
}
It would be even better like this:
foreach (RadioButton rdbtn in myDiv.Controls.OfType<RadioButton>().Where(rdbtn => rdbtn.Checked))
{
}

Adding i value to control name

I have ten labels on a page. I want to make these invisible in a for loop on page load.
I have tried this (doesn't work):
for (int i = 0; i < 10; i++)
{
my_lbl+i.Visible = false;
}
Therefore, it should do:
my_lbl1.Visible = false;
my_lbl2.Visible = false;
my_lbl3.Visible = false;
my_lbl4.Visible = false;
etc...
Is there a way to do this?
Put all of the labels into a collection:
private List<Label> labels = new List<Label>{my_lbl1, my_lbl2, my_lbl3, my_lbl4};
Then you can iterate the whole collection:
foreach(var label in labels)
label.Visible = false;
Make a List of them;
List<Label> yourlabels = new List<Label>{my_lbl1, my_lbl2, my_lbl3...};
and use foreach loop making them visible.
foreach(var label in yourlabels)
{
label.Visible = false;
}
I don't know if there is a better way but this way seems logical to me.
Putting the labels in a collection (as the previous answers have suggested) is a great solution. You can also retrieve the controls by their name using FindControl method of the Page.
for (int i = 0; i < 10; i++)
{
this.FindControl("my_lbl" + i.ToString()).Visible = false;
}
I guess you can utillize Page's FindControl method:
for (int i = 0; i < 10; i++)
{
FindControl(string.Format("my_lbl{0}", i)).Visible = false;
}
But check the case if control is not found of course.
Or, you can put them into dictionary:
Dictionary<string, Label> nameOfDict = new Dictionary<string, Label>();
nameOfDict.Add("label1", label1);
nameOfDict.Add("label2", label2);
For...
nameOfDict ["label" + incrementator].visible = false;
Or, create them dynamically into an array of labels.
If you're sure that, let's say, you want to uncheck all checkboxes in a groupbox, you can do this, too:
foreach (var item in groupBox1.Controls)
{
if (item.GetType() == typeof(CheckBox))
{
((CheckBox)item).Checked = true;
}
}
with LINQ:
foreach (var item in groupBox1.Controls.Cast<object>().Where(item => item.GetType() == typeof(CheckBox)))
{
((CheckBox)item).Checked = true;
}

Accessing dynamically created checkbox in c#

I am creating a few checkboxes when I open a form with the following code:
private void OpenFolder_Load(object sender, EventArgs e)
{
int i = 0;
foreach (string file in filesToOpen)
{
Label lbl = new Label();
lbl.Text = Path.GetFileNameWithoutExtension(file);
lbl.Width = 200;
lbl.Height = 25;
lbl.AutoEllipsis = true;
lbl.Location = new System.Drawing.Point(10, 40 + 25 * i);
this.Controls.Add(lbl);
string checkName = "check" + i;
CheckBox check = new CheckBox();
check.Checked = true;
check.AccessibleName = checkName;
check.Location = new System.Drawing.Point(340, 40 + 25 * i);
check.CheckedChanged +=new EventHandler(check_CheckedChanged);
this.Controls.Add(check);
CheckBoxes.Add(check);
i++;
}
and I am trying to check the state of the checkboxes everytime one changes to toggle my OK button (the user can validate only if there are a certain number of the checkboxes checked)
here is the code I use, but it fails as I am not able to target the checkboxes:
private void check_CheckedChanged(Object sender, EventArgs e)
{
for (int i = 0; i < filesToOpen.Count(); i++)
{
string tbarName = "tbar" + i;
string checkName = "check" + i;
CheckBox ckb = this.Controls.OfType<CheckBox>()
.Where(c => c.AccessibleName.Equals(checkName)) as CheckBox;
TrackBar tkb = this.Controls.OfType<TrackBar>()
.Where(t => t.AccessibleName.Equals(tbarName)) as TrackBar;
//TrackBar tkb = this.Controls.Find(tbarName, false).First() as TrackBar;
//CheckBox ckb = this.Controls.Find(checkName, false).First() as CheckBox;
if (ckb.Checked == true)
{
//do stuff
}
}
}
what am I doing wrong/really wrong?
Given that you add the checkboxes to your own list:
CheckBoxes.Add(check);
it would be simpler to loop over that rather than trying to find the control associated with the file:
foreach (var checkBox in CheckBoxes)
{
if (checkbox.Checked)
{
// Do stuff...
}
}
However, you shouldn't need to use a separate list. This line is wrong:
CheckBox ckb = this.Controls.OfType<CheckBox>()
.Where(c => c.AccessibleName.Equals(checkName)) as CheckBox;
Where returns a IEnumerable<CheckBox> but you are trying to cast it directly to a CheckBox which will return null. What you should have is:
CheckBox ckb = this.Controls.OfType<CheckBox>()
.Where(c => c.AccessibleName.Equals(checkName)).First();
You will still need to check to see if ckb is null (just in case there is nothing on the list) but this should return you the control you are looking for.
Check the type of "this" and then check its Controls collection - your checkboxes are probably a few iterations down the tree.
You'd need some kind of recursive find controls function such as the one found in this article
Iterating over all the checkboxes with every check is not required and is readlly hard processing work. Instead when creating you always know in what state you've created those - so just keep the count of "Checked" checkboxes. When a checkbox being checked increment the count, and when one unchecked - take out 1 from the count. And later have a check: "if (count == requiredCount) {//Logic here}"
So the code will look like:
private int checkedCount;
private void check_CheckedChanged(Object sender, EventArgs e)
{
this.checkedCount += (sender as CheckBox).Checked?1:-1;
if(this.checkedCount == requiredCount)
{
//do stuff
}
}
Good luck with development.

Categories

Resources