collect all selected radio button of some tab pages - c#

I have about 18 tab page, each tab has some radio button.
I want to collect all selected radio button into a DB.
how can I collect them?
i have a button below the form for go forward next tab with colde below:
private void simpleButton2_Click(object sender, EventArgs e)
{
var TabIndex = tabOrthpedic.SelectedTabPageIndex;
if (TabIndex == tabOrthpedic.TabPages.Count - 1)
{
return;
}
tabOrthpedic.SelectedTabPageIndex += 1;
}
also I created an object for selected radio button of each tab as below:
public class Profile
{
public string ProfileNumber;
public string PainOrgan;
public string NeckLoc;
public string BackLoc;
public string LowBackLoc;
public string ShoulderLoc;
public string ElbowLoc;
public string HandLoc;
public string PelvicLoc;
public string KneeLoc;
public string FootLoc;
public string PainRate;
public string PainTime;
public string PainHistory;
public string PainResult;
public string Follow;
public string Expectation;
public string Limitation;
public string DesieseHistory;
}

Add the following class to your project. Using Descendants ensures that if there are other containers on the tab control with radio buttons we can get to them too.
public static class ControlExtensions
{
public static IEnumerable<T> Descendants<T>(this Control control) where T : class
{
foreach (Control child in control.Controls)
{
if (child is T thisControl)
{
yield return (T)thisControl;
}
if (child.HasChildren)
{
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
}
public static RadioButton RadioButtonChecked(this Control control, bool #checked = true)
=> control.Descendants<RadioButton>().ToList().FirstOrDefault((radioButton) => radioButton.Checked == #checked);
}
Usage
foreach (TabPage page in tabControl1.TabPages)
{
RadioButton selected = page.RadioButtonChecked();
if (selected is not null)
{
// We have a selected RadioButton
}
else
{
// no selected RadioButton on TabPage
}
}
Note: this is for conventional Windows Forms controls, don't know about DevExpress.
Full source

Related

How to link textbox and checkbox in C#

I started making a small program. The form contains checkbox1,2,3,4,.... and textbox1,2,3,4,5.... there is a code that looks at which of the checkboxes are marked. If there is any possibility to link textbox and checkbox. So that when a code marked with a checkbox is detected, the text is taken from the textbox given to it and transferred to the RichTextBox, using AppendText. Below is a sample code with a cyclic check of all the checkboxes on the form for the presence of checked on my form.
foreach (Control control in this.tabControl1.TabPages[0].Controls) //цикл по форме с вкладками
{
if (control as CheckBox != null) // проверка на пустое значение
{
if (control.Visible == true)// проверка на видимость
{
if ((control as CheckBox).Checked)// проверка на чек
{
}
else if ((control as CheckBox).Checked == false)
{
}
}
}
Use the following method to get CheckBox controls.
public static class ControlExtensions
{
public static IEnumerable<T> Descendants<T>(this Control control) where T : class
{
foreach (Control child in control.Controls)
{
if (child is T thisControl)
{
yield return (T)thisControl;
}
if (child.HasChildren)
{
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
}
}
In the form, use a Dictionary to pair CheckBox to TextBox. You can also check for visibility in the Where.
public partial class Form1 : Form
{
private readonly Dictionary<string, TextBox> _dictionary =
new Dictionary<string, TextBox>();
public Form1()
{
InitializeComponent();
_dictionary.Add("checkBox1", textBox1);
_dictionary.Add("checkBox2", textBox2);
_dictionary.Add("checkBox3", textBox3);
_dictionary.Add("checkBox4", textBox4);
_dictionary.Add("checkBox5", textBox5);
}
private void button2_Click(object sender, EventArgs e)
{
var list = tabControl1.Descendants<CheckBox>().ToList();
var #checked = list.Where(x => x.Checked).ToList();
var notChecked = list.Where(x => !x.Checked).ToList();
foreach (var checkBox in #checked)
{
TextBox textBox = _dictionary[checkBox.Name];
}
}
}
Create a UserControl with CheckBox and TextBox components. Create properties Checked and TextForAdd:
namespace Sort.UserPanel
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public bool Checked { get { return checkBox1.Checked; } }
public string TextForAdd { get { return textBox1.Text; } }
}
}
On the main form we add UserControl1 the necessary number of times.
private void testCheckBoxes(object obj)
{
if (obj is UserControl1 control)
{
string text = control.TextForAdd;
// .....
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Control control in this.LeftPanel.Controls)
{
if (control as UserControl1 != null)
{
if (control.Visible == true )
{
testCheckBoxes(control);
}
}
}
}

How to clear all Textboxes and ComboBoxes in all UserControls?

I am currently writing a program that when a button is clicked on a final UserControlit clears all the TextBox and ComboBox in all UserControls within the program.
I have created a method within my OverviewControl that I am trying to call on a button that would clear all the Textbox's and ComboBox's within the GeneralControl and StatsControl classes.
MainForm.cs
public MainForm()
{
overviewControl1.GeneralControl = generalControl1;
overviewControl1.StatsControl = statsControl1;
}
OverviewControl.cs
public partial class OverviewControl : UserControl
{
public GeneralControl GeneralControl { get; set; }
public StatsControl StatsControl { get; set; }
private void GeneralSaveButton_Click(object sender, EventArgs e)
{
ClearItems();
}
private void ClearItems()
{
foreach (Control c in GeneralControl?.Controls)
{
if (c is TextBox tb)
tb.Clear();
else if (c is ComboBox cb)
cb.SelectedIndex = -1;
}
foreach (Control c in StatsControl?.Controls)
{
if (c is TextBox tb)
tb.Clear();
else if (c is ComboBox cb)
cb.SelectedIndex = -1;
}
}
}
I am expecting that when I click my button, it calls the GeneralSaveButton_Click() method and it clears all fields from the GeneralControl and StatsControl but all fields remain there after calling the method.
Any help getting pointed in the right direction would be helpful.

Is it possible to list the checkboxes that are checked in a textbox

I have a page where the user can select what toppings they would like, I would then like the next form to have a textbox with all the Checkboxes listed that the user checked in the previous form, is this possible?
I have made it work with one Checkbox checked using the following code,
On form 1,
public static string Cheese = "";
if (CheeseTick.Checked)
{
Cheese = "1 x Extra Cheese";
}
on form 2,
ToppingSummary.Text = Form1.Cheese
Well, it seems that you have to enumarate all the Controls and filter out CheckBoxes of interest:
public class Form1 {
...
public static IEnumerable<Control> AllControls(Control control) {
var controls = control.Controls
.OfType<Control>();
return controls
.SelectMany(ctrl => AllControls(ctrl))
.Concat(controls);
}
public String AllToppings {
get {
var source = AllControls(this)
.OfType<CheckBox>()
.Where(checkbox => checkbox.Checked)
//TODO: put other conditions on checkbox here, e.g.
//.Where(checkbox => checkbox.Name.Contains("Tick"))
.Select(checkbox => checkbox.Text);
return String.Join(" ", source);
}
}
...
}
On the Form2
Form1 form = Application.OpenForms
.OfType<Form1>()
.LastOrDefault();
if (form != null)
ToppingSummary.Text = form.AllToppings;
The Correct way to do this is MVVM, that is that the form has an object on it that has its value set on the form, that change is then picked up on a second form because it has the same object inside it
public class FoodOrder
{
public List<String> SpecialInstructions{get;set;}
public void AddSpecialInstruction(string instruction)
{
SpecialInstructions.Add(instruction);
SpecialInstructionsChanged?.Invoke(this,EventArgs.Empty);
}
public event EventHandler SpecialInstructionsChanged;
}
then in form one CheeseTick.CheckedChanged event calls AddSpecialInstruction or RemoveSpecialInstruction, form two listens to SpecialInstructionsChanged and updates as required
public class Form1
{
public FoodOrder Order {get;set}
}
public class Form2
{
public FoodOrder Order {get;set}
}
then you do form2.Order = Form1.Order just make sure you add a listener to the event after you sent the orders to be equal
if you then wanted to automate the checkbox's you can loop through all the checkboxes in the designated control
foreach(Checkbox c in Control.Controls)
{
c.CheckedChanged += (s,e)=>
{
var cb = s as Checkbox;
if(cb.Checked)
Order.AddSpecialInstruction(cb.Text);
else
Order.RemoveSpecialInstruction(cb.Text);
}
}

Add another dropdown button to own devexpres PopupContainerEdit with same style behaviour

We've got custom PopupContainerEdit that inherits from DevExpress'es PopupContainerEdit. One of our custom features is another dropdown button (EditorButton with kind = ButtonPredefines.Glyph) that acts like the default one except, it opens different PopupContainerControl. Everything works as intended except button's style coloring. The button acts like default button - that means it doesn't support state coloring (checked/unchecked) when dropdown is visible/hidden. I couldn't find any custom draw event/method for EditorButton.
Is it possible to achieve such behaviour? If so, how?
#edit
Simple example of the above situation.
Default PopupContainerEdit looks like image A. When you click on the
button (triangle like), dropdown shows and button goes into checked
state.
Our PopupContainerEdit (that inherits from default) looks like
B.
C, D is coloring example when you hover the button.
E is checked state coloring for default button (it works like that by
DevExpress'es design).
F is our button behaviour - acts like normal button.
G is what we want - checked state coloring for our button
Our approach to create custom button:
string TheToolTipText = "The text";
string OurButtonTag = "TheButton";
Image TheIcon = new Image(); // just example ...
EditorButton customButton = new EditorButton();
customButton.Width = 16;
customButton.Image = TheIcon;
customButton.ToolTip = TheToolTipText;
customButton.Tag = OurButtonTag;
customButton.Kind = ButtonPredefines.Glyph;
this.Properties.Buttons.Add(customButton);
To be honest there's nothing more to show. We're not aware of any custom Draw event or similar things.
There are two properties in RepositoryItemPopupContainerEdit that are responsible for this behavior. Fisrt one is RepositoryItemPopupBase.ActionButtonIndex property. It's value specifying which editor button will open the editor's dropdown window. The second one is RepositoryItemPopupContainerEdit.PopupControl which sets the control to display in the popup window. So, by manipulating with this two properties, you can achieve the desired behavior.
Here is example:
0. RepositoryItemPopupContainerEdit descendant
Because you need to show two different PopupContainerControl
you can create additional properties for each of your controls in your custom RepositoryItem.
public class RepositoryItemCustomEdit1 : RepositoryItemPopupContainerEdit
{
#region Some default stuff for custom repository item (constructors, registration, etc).
static RepositoryItemCustomEdit1() { RegisterCustomEdit1(); }
public const string CustomEditName = "CustomEdit1";
public RepositoryItemCustomEdit1() { }
public override string EditorTypeName { get { return CustomEditName; } }
public static void RegisterCustomEdit1()
{
Image img = null;
EditorRegistrationInfo.Default.Editors.Add(new EditorClassInfo(
CustomEditName,
typeof(CustomEdit1),
typeof(RepositoryItemCustomEdit1),
//For v13.2 you need to use custom ViewInfo class. So, here is CustomEdit1ViewInfo.
//For v15.1 you can use the base PopupContainerEditViewInfo.
typeof(CustomEdit1ViewInfo),
new ButtonEditPainter(),
true,
img));
}
#endregion
#region Hide base PopupContainerControl properties in designer.
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override PopupContainerControl PopupControl
{
get { return base.PopupControl; }
set { base.PopupControl = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override int ActionButtonIndex
{
get { return base.ActionButtonIndex; }
set { base.ActionButtonIndex = value; }
}
#region
#region First PopupContainerControl properties
public int DefaultActionButtonIndex { get; set; }
public PopupContainerControl DefaultPopupControl { get; set; }
#endregion
#region Another PopupContainerControl properties
public int DifferentActionButtonIndex { get; set; }
public PopupContainerControl DifferentPopupControl { get; set; }
#endregion
public override void Assign(RepositoryItem item)
{
BeginUpdate();
try
{
base.Assign(item);
RepositoryItemCustomEdit1 source = item as RepositoryItemCustomEdit1;
if (source == null) return;
DefaultActionButtonIndex = source.DefaultActionButtonIndex;
DefaultPopupControl = source.DefaultPopupControl;
DifferentPopupControl = source.DifferentPopupControl;
DifferentActionButtonIndex = source.DifferentActionButtonIndex;
}
finally
{
EndUpdate();
}
}
}
You can see new properties in your designer:
1. PopupContainerEdit descendant
Now you can use this properties in your custom Edit class.
public class CustomEdit1 : PopupContainerEdit
{
#region Some default stuff for custom edit (constructors, registration, etc).
static CustomEdit1() { RepositoryItemCustomEdit1.RegisterCustomEdit1(); }
public CustomEdit1() { }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public new RepositoryItemCustomEdit1 Properties { get { return base.Properties as RepositoryItemCustomEdit1; } }
public override string EditorTypeName { get { return RepositoryItemCustomEdit1.CustomEditName; } }
#endregion
protected override bool IsActionButton(EditorButtonObjectInfoArgs buttonInfo)
{
int buttonIndex = Properties.Buttons.IndexOf(buttonInfo.Button);
if (buttonIndex == Properties.DefaultActionButtonIndex ||
buttonIndex == Properties.DifferentActionButtonIndex)
{
//Set the Properties.ActionButtonIndex value according to which button is pressed:
Properties.ActionButtonIndex = buttonIndex;
//Set the Properties.PopupControl according to which button is pressed:
if (buttonIndex == Properties.DefaultActionButtonIndex)
Properties.PopupControl = Properties.DefaultPopupControl;
else
Properties.PopupControl = Properties.DifferentPopupControl;
return true;
}
return false;
}
}
2. PopupContainerEditViewInfo descendant
For v13.2 you need to use custom ViewInfo class for your editor:
public class CustomEdit1ViewInfo : PopupContainerEditViewInfo
{
public CustomEdit1ViewInfo(RepositoryItem item) : base(item) { }
public new RepositoryItemPopupBase Item { get { return base.Item as RepositoryItemCustomEdit1; } }
//Show the pressed state when button is pressed or when popup is open.
protected override bool IsButtonPressed(EditorButtonObjectInfoArgs info)
{
var hitObject = PressedInfo.HitObject as EditorButtonObjectInfoArgs;
return
(hitObject != null && hitObject.Button == info.Button) ||
(IsPopupOpen && Item.ActionButtonIndex == info.Button.Index);
}
}
Result
In the result you will get something like this:
and

Working with multiple files in C#

I am facing special problem.
I have a button, which when clicked, will cause click event to open file dialog to choose file. Name of this file (SafeFileName) will be displayed in combo box. Then I read first 9 rows of that file and store them as struct of this type:
public struct DCM_INFO
{
public string FILE_NAME;
public string FILE_PATH;
public string VERSION;
public string NAME;
public string DATE;
public string BOX;
public string SERIAL_NUM;
public string SERIES;
public string POINT;
public string NOTE;
public string VARIANT;
}
First two strings are "SafeFileName" and "FileName".
This struct is then displayed in ListView.
And now the thing I want to do:
After I open second file with exact the same button click event, I want to add second "SafeFileName" to combobox and make it visible(displayed on top), then save data from file in DCM_INFO struct with different name than the first one. After this, If i choose different file than actively displayed in combo box, listview will be updated with adequate data from DCM_INFO struct.
I have figured out the part with combo box (display active file) but how to properly switch between listviews ?
You could overwrite the ToString method in the struct and add the struct directly to the combobox. In the SelectionCheangeCommited Event of the ComboBox you could extract the item (cast it back to the struct) and create the appropriate ListViewItems which are then added to your ListView (after clearing the ListViews Items collection)
public struct DCM_INFO
{
public string FILE_NAME;
public string FILE_PATH;
public string VERSION;
public string NAME;
public string DATE;
public string BOX;
public string SERIAL_NUM;
public string SERIES;
public string POINT;
public string NOTE;
public string VARIANT;
public override string ToString()
{
return FILE_NAME;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.comboBox1.SelectedItem != null)
{
DCM_INFO item = (DCM_INFO)this.comboBox1.SelectedItem;
// Create ListViewItems and add them to ListView
}
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
DialogResult ret = ofd.ShowDialog();
if (ret == System.Windows.Forms.DialogResult.OK)
{
DCM_INFO tmp = new DCM_INFO();
// read file and fill struct
this.comboBox1.Items.Add(tmp);
}
}
}

Categories

Resources