C# Shorten Button Assigned to Reset Values - c#

I've just started programming meaning I'm new... I've made a tic tac toe game using else if statements.
The code below is code that will reset certain values within my game, I'm sure there's but I can't find an answer - How do I shorten this block of code?
btn1.Enabled = true;
btn2.Enabled = true;
btn3.Enabled = true;
btn4.Enabled = true;
btn5.Enabled = true;
btn6.Enabled = true;
btn7.Enabled = true;
btn8.Enabled = true;
btn9.Enabled = true;
btn1.Text = "";
btn2.Text = "";
btn3.Text = "";
btn4.Text = "";
btn5.Text = "";
btn6.Text = "";
btn7.Text = "";
btn8.Text = "";
btn9.Text = "";
btn1.BackColor = default(Color);
btn2.BackColor = default(Color);
btn3.BackColor = default(Color);
btn4.BackColor = default(Color);
btn5.BackColor = default(Color);
btn6.BackColor = default(Color);
btn7.BackColor = default(Color);
btn8.BackColor = default(Color);
btn9.BackColor = default(Color);

You should use an array, or better yet, a generic list which will hold all your buttons.
For example:
List<Button> buttonList = new List<Button>();
// Add buttons to list...
buttonList.Add(btn1);
buttonList.Add(btn2);
...
Then, you can iterate on the list like this:
foreach (Button btn in buttonList)
{
btn.Text = "";
btn.BackColor = default(Color);
}
The code above will run on all the buttons in the list and for each of them clear the text and set the BackColor.

This should be done with arrays, instead of btn1, you would have btn[], and then you can access them with a for loop:
for (i=0; i<9; i++) {
btn[i].Enabled = true;
btn[i].Text = "";
btn[i].Color = default(Color);
}
and these 5 lines of code contain all the code you have above.

reset for all button at control
foreach(var item in this.Controls)
{
if (item is Button)
{
item.Enabled = true;
item.Text = "";
item.BackColor = default(Color);
}
}

Related

Need solution to remove duplicate code in C#

I'm using this right now to clear a tic tac toe table on Microsoft Windows Forms
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";
but it's too long so I wanted to use a for loop like this
for (int i = 1; i < 10; i++)
{
button[i].Enable = true;
button[i].Text = "";
}
but it doesn't work so could anyone suggest a solution?
you can iterate over Controls array of parent of buttons, for example you can move all buttons to a Panel and use foreach to iterate over all controls inside it:
foreach(var control in Panel1.Controls) {
if (control is Button button)
{
button.Text = "";
button.Enabled = true;
}
}
I see what you are thinking, but you cannot dynamically change the name of the variable you are trying to edit in a for loop like that.
In a for loop, it will iterate through a starting value until it reaches a stopping condition. for loops are great for when you have a data structure like a List or an Array where you can enumerate through to get or set values.
The code you have for the for loop is starting to enumerate through either an Array or List that has a name of button. To fix this, I recommend to add the buttons to an Array and then you can use a foreach loop to set the values:
foreach (Button button in buttons){
button.Enabled = true;
button.Text = "";
}

How to define condition for Radiobutton in a efficient way?

i`m trying to find a efficient way to define conditions for radio-buttons.
After selecting a Radio-Button i should disable or fill the text-boxes. Following an example:
private void Transportauftrag_CheckedChanged(object sender, EventArgs e)
{
groupBox1.Visible = true;
groupBox8.Visible = false;
StartGerät.Text = "";
StartBlockFach.Text = "";
StartTiefe.Text = "";
ZielGerät.Text = "";
ZielBlockFach.Text = "";
ZielTiefe.Text = "";
FehlerFehler.Text = "****";
FehlerBereich.Text = "****";
FehlerInfo.Text = "****";
Transportbefehl.Text = "";
Breite.Text = "";
Tiefe.Text = "";
Höhe.Text = "";
Typ.Text = "";
Folgeauftrag.Text = "";
Behälternummer.Text = "";
Reserve.Text = "";
StartGerät.Enabled = true;
StartBlockFach.Enabled = true;
StartTiefe.Enabled = true;
ZielGerät.Enabled = true;
ZielBlockFach.Enabled = true;
ZielTiefe.Enabled = true;
FehlerFehler.Enabled = false;
FehlerBereich.Enabled = false;
FehlerInfo.Enabled = false;
Transportbefehl.Enabled = true;
Breite.Enabled = true;
Tiefe.Enabled = true;
Höhe.Enabled = true;
Typ.Enabled = true;
Folgeauftrag.Enabled = true;
Behälternummer.Enabled = true;
Reserve.Enabled = true;
}
So now i should do this 7 times.
And for this i need over 400 Line of Codes in my WindowsFormsApp-File.
Are they any better way / solution to do this?
ok here are some suggestions. Basically if faced with such a problem then it indicates that you need an organizational structure. Otherwise one gets lost. As it appears from the picture of your GUI you already have GroupBoxes that organize this. All the labels and Textboxes inside that groupbox are in groupBox1.Controls. You can get them out in 1 blow even by type:
List<TextBox> allTextBoxesFromGroupBox1 = groupBox1.Controls.OfType<TextBox>().ToList();
Now you can iterate over it and write the same value for each Textbox:
foreach (TextBox tb in allTextBoxesFromGroupBox1)
{
tb.Text = "";
}
But you better make a method from it:
private void FillAllTextBoxes(GroupBox groupBox, string text)
{
List<TextBox> allTextBoxesFromGroupBox1 = groupBox.Controls.OfType<TextBox>().ToList();
foreach (TextBox tb in allTextBoxesFromGroupBox1)
{
tb.Text = "";
}
}
Now you can simply call it and pass the necessary input:
FillAllTextBoxes(groupBoxStart, "");
FillAllTextBoxes(groupBoxZiel, "");
FillAllTextBoxes(groupBoxFehler, "****");
FillAllTextBoxes(groupBoxParameter, "");
At this point we got rid of 17 Lines and introduced only 4
Proceeding... The next step would be the enabling of the controls. It seems that you treat again all Textboxes inside the same groupbox also the same. So we can introduce another parameter for the enabling part into the method:
private void FillAllTextBoxes(GroupBox groupBox, string text, bool enable)
{
List<TextBox> allTextBoxesFromGroupBox1 = groupBox.Controls.OfType<TextBox>().ToList();
foreach (TextBox tb in allTextBoxesFromGroupBox1)
{
tb.Text = "";
tb.Enabled = enable;
}
}
and this allows us to remove the rest of the lines entirely without introducing new lines of code:
FillAllTextBoxes(groupBoxStart, "", true);
FillAllTextBoxes(groupBoxZiel, "", true);
FillAllTextBoxes(groupBoxFehler, "****", false);
FillAllTextBoxes(groupBoxParameter, "", true);
So now you are down at 4 lines (I see only 4 groupboxes in your screenshot) of code

C# did not accepting checked property

try
{
DataRowView drv = attDataGrid.SelectedItem as DataRowView;
att_id = Convert.ToInt32(drv.Row[0].ToString());
attComboBox.SelectedItem = drv.Row[1].ToString();
rdata = drv.Row[2].ToString(); ;
attDetail.Text = drv.Row[4].ToString();
DateTime sdt = dc.changeDateG(drv.Row[3].ToString());
if(rdata.Equals("حاضر"))
{
attPre.Checked = true;
}
else {
attUp.Checked = true;
}
try
{
attDate.SelectedDate = sdt;
}
catch (FormatException)
{
MessageBox.Show(sdt.ToString());
}
}
catch(NullReferenceException)
{
}
I am trying to set my attPre radio button checked but visual studio takes it as error any idea how to deal with this error???
Probably because you doing comparision not assignment
Use this:
attPre.Checked = true;
Instead of
attPre.Checked == true;
I have found out how to deal with it
RadioButton pr = attPre as RadioButton;
pr.IsChecked = true;

Where do I put these visible changes for them to display

I have my code written like so:
private void radioSelectButton_Click(object sender, EventArgs e)
{
if (pteriRadio.Checked) // Selecting avatar to be displayed from here on out.
//This avatar will also be displayed on the game board.
{
pteriBox1.Visible = true;
xweetokBox1.Visible = false;
ixiBox1.Visible = false;
label1.Text = ("Pteri Inventory");
player1avatar = "pteri";
}
else if (xweetokRadio.Checked)
{
xweetokBox1.Visible = true;
pteriBox1.Visible = false;
ixiBox1.Visible = false;
label1.Text = ("Xweetok Inventory");
player1avatar = "xweetok";
}
else if (ixiRadio.Checked)
{
ixiBox1.Visible = true;
pteriBox1.Visible = false;
xweetokBox1.Visible = false;
label1.Text = ("Ixi Inventory");
player1avatar = "ixi";
}
characterSelectBox.Visible = false;
radioSelectButton.Visible = false;
characterSelectBox2.Visible = true;
radioSelectButton2.Visible = true;
}
It seems as though the visibility changes should display when I have it like this, with the changes within the button click but outside of the if statements (It doesn't matter what the user selects, once selected the option to select needs to disappear for that user.)Yet the visibility changes don't execute. What am I missing here?
If I nest the if-statements as suggested by a previous person, here's what I have:
private void radioSelectButton_Click(object sender, EventArgs e)
{
if (pteriRadio.Checked) // Selecting avatar to be displayed from here on out.
//This avatar will also be displayed on the game board.
{
pteriBox1.Visible = true;
xweetokBox1.Visible = false;
ixiBox1.Visible = false;
label1.Text = ("Pteri Inventory");
player1avatar = "pteri";
if (xweetokRadio.Checked)
{
xweetokBox1.Visible = true;
pteriBox1.Visible = false;
ixiBox1.Visible = false;
label1.Text = ("Xweetok Inventory");
player1avatar = "xweetok";
if (ixiRadio.Checked)
{
ixiBox1.Visible = true;
pteriBox1.Visible = false;
xweetokBox1.Visible = false;
label1.Text = ("Ixi Inventory");
player1avatar = "ixi";
}
characterSelectBox.Visible = false;
radioSelectButton.Visible = false;
characterSelectBox2.Visible = true;
radioSelectButton2.Visible = true;
}
}
}
Now, not only do the visible items not swap over, two of the character choices don't display.
It looks like the radio buttons here can be checked/unchecked together. I think you should use separate if statements for each condition instead of else if.
You need to Invalidate your form to make it redraw after you change the properties. Assuming the radioSelectButton_Click method is in the same form, calling this.Invalidate() at the end of the method should force the redraw.

RadioButtonList: OnSelectedIndexChanged not firing

I have an aspx page where i dynamically add a radiobuttonlist with OnSelectedIndexChanged event. In the event i check for the selected items. i have 2 items.
For the first item,the event is firing well, However if i choose the other option the event is not firing: below the code..
The event is only firing is i change from "Some provided" to "All provided" the other way it is not working
Adding the RBL:
RadioButtonList dControl_b = new RadioButtonList();
dControl_b.ID = "rbl_MinCriteria";
dControl_b.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
dControl_b.CssClass = "Font";
dControl_b.Font.Name = "Arial";
dControl_b.Font.Size = 8;
dControl_b.ToolTip = "";
dControl_b.SelectedIndex = -1;
dControl_b.SelectedIndexChanged += new EventHandler(rbl_MinCriteria_SelectedIndexChanged);
dControl_b.AutoPostBack = true;
Checking the selected item:
if(rbl_MinCriteria.SelectedItem.ToString() == "All provided")
{
cbl_MinimumCriteria.Items[0].Selected = true;
cbl_MinimumCriteria.Items[1].Selected = true;
cbl_MinimumCriteria.Items[2].Selected = true;
cbl_MinimumCriteria.Items[3].Selected = true;
cbl_MinimumCriteria.Enabled = false;
//*************************************************************
if (ddl_CountryOccurence.SelectedValue != "Please choose")
{
ddl_CountryOccurence.Enabled = false;
}
else
{
ddl_CountryOccurence.Enabled = true;
}
//*************************************************************
if (tb_DueDate.Text != "")
{
tb_DueDate.Enabled = false;
}
else
{
tb_DueDate.Enabled = true;
}
OtherControlI.Enabled = false;
OtherControlII.Enabled = false;
OtherControlIII.Enabled = false;
}
if (rbl_MinCriteria.SelectedItem.ToString() == "Some provided")
{
cbl_MinimumCriteria.Items[0].Selected = false;
cbl_MinimumCriteria.Items[1].Selected = false;
cbl_MinimumCriteria.Items[2].Selected = false;
cbl_MinimumCriteria.Items[3].Selected = false;
cbl_MinimumCriteria.Enabled = true;
//*************************************************************
if (ddl_CountryOccurence.SelectedValue != "Please choose")
{
ddl_CountryOccurence.Enabled = false;
}
else
{
ddl_CountryOccurence.Enabled = true;
}
//*************************************************************
if (tb_DueDate.Text != "")
{
tb_DueDate.Enabled = false;
}
else
{
tb_DueDate.Enabled = true;
}
OtherControlI.Enabled = false;
OtherControlI.SelectedIndex = -1;
OtherControlII.Enabled = false;
OtherControlII.SelectedIndex = -1;
OtherControlIII.Enabled = false;
OtherControlIII.SelectedIndex = -1;
}
Any help and Comment is much appreciated
This is for people who find this question from Google:
On the RadioButtonList, set the AutoPostBack property to true.
RadioButtonList OnSelectedIndexChanged
I have this problem and solved it.
For raising onselectedindexchanged event of RadioButtonList , check below items:
<asp:RadioButtonList ID="rdlCondition" runat="server" AutoPostBack="True"
onselectedindexchanged="rdlCondition_SelectedIndexChanged">
and in the Page_Load set them with code :
rdlCondition.AutoPostBack = true;
rdlCondition.SelectedIndexChanged += new EventHandler (rdlCondition_SelectedIndexChanged);
Looking at the code above there seems to be alot of code reuse. I reorganized your code a bit (assuming you didnt leave anything out). Keep in mind I never tested it.
protected void rbl_MinCriteria_SelectedIndexChanged(object sender,EventArgs e)
{
if (rbl_MinCriteria.SelectedIndex<0) return; //If nothing is selected then do nothing
OtherControlI.Enabled = false;
OtherControlII.Enabled = false;
OtherControlIII.Enabled = false;
if(rbl_MinCriteria.SelectedItem.ToString() == "All provided")
{
cbl_MinimumCriteria.Items[0].Selected = true;
cbl_MinimumCriteria.Items[1].Selected = true;
cbl_MinimumCriteria.Items[2].Selected = true;
cbl_MinimumCriteria.Items[3].Selected = true;
cbl_MinimumCriteria.Enabled = false;
}
if (rbl_MinCriteria.SelectedItem.ToString() == "Some provided")
{
cbl_MinimumCriteria.Items[0].Selected = false;
cbl_MinimumCriteria.Items[1].Selected = false;
cbl_MinimumCriteria.Items[2].Selected = false;
cbl_MinimumCriteria.Items[3].Selected = false;
cbl_MinimumCriteria.Enabled = true;
OtherControlI.SelectedIndex = -1;
OtherControlII.SelectedIndex = -1;
OtherControlIII.SelectedIndex = -1;
}
//*************************************************************
if (ddl_CountryOccurence.SelectedValue != "Please choose")
{
ddl_CountryOccurence.Enabled = false;
}
else
{
ddl_CountryOccurence.Enabled = true;
}
//*************************************************************
if (tb_DueDate.Text != "")
{
tb_DueDate.Enabled = false;
}
else
{
tb_DueDate.Enabled = true;
}
}
I know this doesn't help your current problem but this is just a suggestion. If you could post the code where your actually adding the values to the list I could help a bit more.
EDIT: Your problem could be your not setting the value of your items, only the text. Try using rbl_MinCriteria.SelectedItem.Text =="All provided" instead.
I've made a sample aspx page, and added one panel in .aspx like below:
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
And in code behind, I've added following code:
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList dControl_b = new RadioButtonList();
dControl_b.ID = "rbl_MinCriteria";
dControl_b.RepeatDirection = System.Web.UI.WebControls.RepeatDirection.Horizontal;
dControl_b.CssClass = "Font";
dControl_b.Font.Name = "Arial";
dControl_b.Font.Size = 8;
dControl_b.ToolTip = "";
dControl_b.SelectedIndex = -1;
dControl_b.SelectedIndexChanged += new EventHandler(rbl_MinCriteria_SelectedIndexChanged);
dControl_b.AutoPostBack = true;
dControl_b.Items.Add(new ListItem("All provided"));
dControl_b.Items.Add(new ListItem("Some provided"));
Panel1.Controls.Add(dControl_b);
}
protected void rbl_MinCriteria_SelectedIndexChanged(object sender,EventArgs e)
{
RadioButtonList rbl_MinCriteria = (RadioButtonList)Panel1.FindControl("rbl_MinCriteria");
if(rbl_MinCriteria.SelectedItem.ToString() == "All provided")
{
}
if (rbl_MinCriteria.SelectedItem.ToString() == "Some provided")
{
}
}
The event is FIRING EVERY TIME the radio button listitem is changed.
So, I'm afraid, you have done something wrong elsewhere. Good luck.

Categories

Resources