I'm new to tinkering with C#, and so far that's the extent of it. I'm just tinkering for a small project I have.
The redundancy is driving me crazy, though. Writing long lists of similar code taking up line after line just doesn't sit well with me.
I have a few tabs with checkboxes and radio buttons in them, that's where I noticed the duplication the most. Unfortunately I... don't quite grasp every aspect of C# as well as I should, yet. So I was hoping to learn from you folks.
Example:
//setup checkbox
checkBox1.AutoSize = true;
checkBox1.Checked = false;
checkBox1.CheckState = CheckState.Unchecked;
checkBox1.Location = new Point(5, 102);
checkBox1.Text = "Check Box 1!";
checkBox1.UseVisualStyleBackColor = true;
//set radio 1
radio1.AutoSize = true;
radio1.Checked = true;
radio1.Location = new Point(5, 33);
radio1.Size = new Size(20, 20);
radio1.Text = "Radio-e-o-e-o";
radio1.UseVisualStyleBackColor = true;
//set radio 2
radio2.AutoSize = true;
radio2.Checked = false;
radio2.Location = new Point(5, 56);
radio2.Size = new Size(18, 20);
radio2.Text = "Option 2!";
radio2.UseVisualStyleBackColor = true;
My instinct would be to set up some arrays with the variable data for things like the names and the distinct data. But as I said, I'm very new, I've only been tinkering... and the resources I've come across tend to either not match what I'm looking for, or add layers of complexity I'm probably not ready for.
If I got your question right: you can make a method:
private CheckBox DoSomethingWith(CheckBox checkBox, Point location, string text)
{
checkBox.AutoSize = true;
checkBox.Checked = false;
checkBox.CheckState = CheckState.Unchecked;
checkBox.Location = location;
checkBox.Text = text;
checkBox.UseVisualStyleBackColor = true;
return checkBox;
}
then pass a checkbox to it checkBox1 = DoSomethingWith(checkBox1, new Point(10,10), "My Text");
You can make your own class that inherits from RadioButton, set your default settings, and use it.
public class MyRadioButton : public RadioButton
{
MyRadioButton()
{
UseVisualStyleBackColor = true;
AutoSize = true;
}
}
Then you just add this control instead of RadioButton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With