Hello I have just recently finished a code of a grid. The instructions allow you to go right,left,up or down and enter a specific value to move by. The problem right now however is, which value is entered is the only location that becomes true. I'm trying to get the entire amount to become true. For example fi we move right 3, it should be 3 spots = true instead of just the last. Can anyone help me with that?
// Make a bool 2d array and save already drilled values into the array
bool[,] drill = new bool[401, 200];
drill[200, 1] = true;
drill[200, 2] = true;
drill[200, 3] = true;
drill[201, 3] = true;
drill[202, 3] = true;
drill[203, 3] = true;
drill[203, 4] = true;
drill[203, 5] = true;
drill[204, 5] = true;
drill[205, 5] = true;
drill[205, 4] = true;
drill[205, 3] = true;
drill[206, 3] = true;
drill[207, 3] = true;
drill[207, 4] = true;
drill[207, 5] = true;
drill[207, 6] = true;
drill[207, 7] = true;
drill[206, 7] = true;
drill[205, 7] = true;
drill[204, 7] = true;
drill[203, 7] = true;
drill[202, 7] = true;
drill[201, 7] = true;
drill[200, 7] = true;
drill[199, 7] = true;
drill[199, 6] = true;
drill[199, 5] = true;
// Set some values
bool okay = true;
int column = -1;
int row = -5;
int check_column = 199;
int check_row = 5;
// Run a while loop
do
{
// Ask the user to input a direction
Console.WriteLine("Which direction would you like to go?");
string direction = Console.ReadLine();
// Ask the user to input a movement
Console.WriteLine("What value would you like to move by?");
string distance = Console.ReadLine();
int new_distance = Convert.ToInt32(distance);
// Use if statements
if (direction == "l" || direction == "L")
{
column = column - new_distance;
check_column = check_column - new_distance;
}
else if (direction == "u" || direction == "U")
{
row = row + new_distance;
check_row = check_row - new_distance;
}
else if (direction == "r" || direction == "R")
{
column = column + new_distance;
check_column = check_column + new_distance;
}
else if (direction == "d" || direction == "D")
{
row = row - new_distance;
check_row = check_row + new_distance;
}
else if (direction == "q" || direction == "Q" || new_distance == 0)
{
Console.WriteLine("Program will now end.");
okay = false;
break;
}
while (new_distance > 0)
{
if (drill[check_column, check_row] == true && check_row >= 0 && check_row <=200 && check_column >=0 && check_column <=400 && drill[check_column, check_row] != true)
{
Console.WriteLine("{0},{1} safe", column, row);
break;
}
else
{
Console.WriteLine("{0},{1} danger", column, row);
Console.WriteLine("Program will now end.");
okay = false;
break;
}
}
} while (okay);
if (okay == false)
{
Console.WriteLine("Thanks for using the program!");
}
Console.ReadLine();
To answer you question, the reason you are not seeing each move as safe is because you are not checking each position, you were simply setting your check position to the position you wanted to move and not each incremental position. I have added a class with a bit more logic in this answer because each move in your game requires slightly different logic to work.
public class DrillGame
{
private const int Columns = 401;
private const int Rows = 200;
public void Play()
{
// Make a bool 2d array and save already drilled values into the array
bool[,] drill = ProvideDrill();
// Set some values
bool okay = true;
_currentGameRow = -1;
_currentGameColumn = -5;
_currentArrayRow = 5;
_currentArrayColumn = 199;
// Run a while loop
do
{
// Ask the user to input a direction
Console.WriteLine("Which direction would you like to go?");
string direction = Console.ReadLine();
// Ask the user to input a movement
Console.WriteLine("What value would you like to move by?");
string distanceInput = Console.ReadLine();
int distanceToMove = Convert.ToInt32(distanceInput);
// Use if statements
if (direction == "l" || direction == "L")
{
okay = TryMoveLeft(distanceToMove);
}
else if (direction == "u" || direction == "U")
{
okay = TryMoveUp(distanceToMove);
}
else if (direction == "r" || direction == "R")
{
okay = TryMoveRight( distanceToMove);
}
else if (direction == "d" || direction == "D")
{
okay = TryMoveDown(distanceToMove);
}
else if (direction == "q" || direction == "Q" || distanceToMove == 0)
{
Console.WriteLine("Program will now end.");
okay = false;
break;
}
} while (okay);
if (okay == false)
{
Console.WriteLine("Thanks for using the program!");
}
Console.ReadLine();
}
private bool TryMoveLeft(int distanceToMove)
{
while(distanceToMove > 0)
{
_currentArrayColumn = _currentArrayColumn - 1;
_currentGameColumn = _currentGameColumn - 1;
if (!TryMoveColumn(distanceToMove))
{
return false;
}
distanceToMove--;
}
return true;
}
private bool TryMoveRight(int distanceToMove)
{
while (distanceToMove > 0)
{
_currentArrayColumn = _currentArrayColumn + 1;
_currentGameColumn = _currentGameColumn + 1;
if (!TryMoveColumn(distanceToMove))
{
return false;
}
distanceToMove--;
}
return true;
}
private bool TryMoveUp(int distanceToMove)
{
while (distanceToMove > 0)
{
_currentArrayRow = _currentArrayRow - 1;
_currentGameRow = _currentGameRow - 1;
if (!TryMoveRow(distanceToMove))
{
return false;
}
distanceToMove--;
}
return true;
}
private bool TryMoveDown(int distanceToMove)
{
while (distanceToMove > 0)
{
_currentArrayRow = _currentArrayRow + 1;
_currentGameRow = _currentGameRow + 1;
if (!TryMoveRow(distanceToMove))
{
return false;
}
distanceToMove--;
}
return true;
}
private bool TryMoveColumn(int distanceToMove)
{
var drill = ProvideDrill();
if (_currentArrayColumn >= 0 && _currentArrayColumn < Columns && drill[_currentArrayColumn, _currentArrayRow])
{
Console.WriteLine($"{_currentGameColumn},{_currentGameRow} safe");
return true;
}
else
{
Console.WriteLine($"{_currentGameColumn},{_currentGameRow} danger");
Console.WriteLine("Program will now end.");
return false;
}
}
private bool TryMoveRow(int distanceToMove)
{
var drill = ProvideDrill();
if (_currentArrayRow >= 0 && _currentArrayRow < Rows && drill[_currentArrayColumn, _currentArrayRow])
{
Console.WriteLine($"{_currentGameColumn},{_currentGameRow} safe");
return true;
}
else
{
Console.WriteLine($"{_currentGameColumn},{_currentGameRow} danger");
Console.WriteLine("Program will now end.");
return false;
}
}
private bool[,] ProvideDrill()
{
bool[,] drill = new bool[Columns, Rows];
drill[200, 1] = true;
drill[200, 2] = true;
drill[200, 3] = true;
drill[201, 3] = true;
drill[202, 3] = true;
drill[203, 3] = true;
drill[203, 4] = true;
drill[203, 5] = true;
drill[204, 5] = true;
drill[205, 5] = true;
drill[205, 4] = true;
drill[205, 3] = true;
drill[206, 3] = true;
drill[207, 3] = true;
drill[207, 4] = true;
drill[207, 5] = true;
drill[207, 6] = true;
drill[207, 7] = true;
drill[206, 7] = true;
drill[205, 7] = true;
drill[204, 7] = true;
drill[203, 7] = true;
drill[202, 7] = true;
drill[201, 7] = true;
drill[200, 7] = true;
drill[199, 7] = true;
drill[199, 6] = true;
drill[199, 5] = true;
return drill;
}
private int _currentArrayRow;
private int _currentArrayColumn;
private int _currentGameRow;
private int _currentGameColumn;
}
Sample output
Related
I'm currently in the process of making mine sweeper for a class project. I have got most of the fundamentals but when I click on an edge button, because it checks all buttons around it, the code crashes when there is no index value. E.g. When x is equal to 10 but the code calls for buttonArray[x + 1, y]. Its a null value and just crashes. Any Ideas on how to fix this? Code is included...
decimal MineCount = 0;
#region MineCount
if ((buttonArray[x + 1, y] != null) && (isMine[x + 1, y] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x + 1, y + 1] != null) && (isMine[x + 1, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x + 1, y - 1] != null) && (isMine[x + 1, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x, y + 1] != null) && (isMine[x, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x, y - 1] != null) && (isMine[x, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y - 1] != null) && (isMine[x - 1, y - 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y] != null) && (isMine[x - 1, y] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
if ((buttonArray[x - 1, y + 1] != null) && (isMine[x - 1, y + 1] == true))
{
isNeighbour[x, y] = true;
isBlank[x, y] = false;
MineCount += 1m;
}
You can use this function for this, instead of duplicate code.
The point of the function is to use limited boundaries.
void CountCells()
{
for(int ix = Math.Max(x - 1, 0); ix <= Math.Min(x + 1, isMine.GetLength(0)); ix++)
{
for(int iy = Math.Max(y - 1, 0); iy <= Math.Min(y + 1, isMine.GetLength(1)); iy++)
{
if ((buttonArray[ix,iy] != null) && isMine[ix,iy])
{
isNeighbour[ix, iy] = true;
isBlank[ix, iy] = false;
MineCount += 1m;
}
}
}
}
Hope it's can be helpfull!
I'm trying to make a basic noughts and crosses game in c#.
So far I've made the grid using buttons which's text changes when it is pressed depending which player's turn it is.
The part which I am stuck on is checking if any of the players has won, I've written this however it doesn't seem to do anything.
private void Form1_Load(object sender, EventArgs e)
{
if (button1.Text == "X" && button5.Text == "X" && button9.Text == "X")
{
MessageBox.Show("Player", player_turntxt.Text + " wins");
Application.Restart();
}
}
private void button1_Click(object sender, EventArgs e)
{
int Player_Turn = Convert.ToInt32(player_turntxt.Text);
if (Player_Turn == 1)
{
button1.Text = "X";
player_turntxt.Text = "2";
button1.Enabled = false;
return;
}
else
{
button1.Text = "O";
player_turntxt.Text = "1";
button1.Enabled = false;
return;
}
(The Application.Restart(); is just a temporary method of checking if it works.)
This is just one of 8 statements which I'll have to make as conditions for victory, any idea where I'm going wrong?
Update:
public void CheckForWinner(int x)
{
if (button1.Text == "X" && button5.Text == "X" && button9.Text == "X")
{
x = 1;
}
else if (button3.Text == "X" && button5.Text == "X" && button7.Text == "X")
{
x = 1;
}
else if (button1.Text == "X" && button4.Text == "X" && button7.Text == "X")
{
x = 1;
}
else if (button2.Text == "X" && button5.Text == "X" && button8.Text == "X")
{
x = 1;
}
else if (button3.Text == "X" && button6.Text == "X" && button9.Text == "X")
{
x = 1;
}
else if (button1.Text == "X" && button2.Text == "X" && button3.Text == "X")
{
x = 1;
}
else if (button4.Text == "X" && button5.Text == "X" && button6.Text == "X")
{
x = 1;
}
else if (button7.Text == "X" && button8.Text == "X" && button9.Text == "X")
{
x = 1;
}
if (button1.Text == "O" && button5.Text == "O" && button9.Text == "O")
{
x = 2;
}
else if (button3.Text == "O" && button5.Text == "O" && button7.Text == "O")
{
x = 2;
}
else if (button1.Text == "O" && button4.Text == "O" && button7.Text == "O")
{
x = 2;
}
else if (button2.Text == "O" && button5.Text == "O" && button8.Text == "O")
{
x = 2;
}
else if (button3.Text == "O" && button6.Text == "O" && button9.Text == "O")
{
x = 2;
}
else if (button1.Text == "O" && button2.Text == "O" && button3.Text == "O")
{
x = 2;
}
else if (button4.Text == "O" && button5.Text == "O" && button6.Text == "O")
{
x = 2;
}
else if (button7.Text == "O" && button8.Text == "O" && button9.Text == "O")
{
x = 2;
}
}
You should create a method to check if any player has won, and run it at the end of everyone of your "button clicks".
I algo suggest you to remove the "return"'s from your button clicks. They can introduce unexpected behaviors sometimes, like ending the function before you execute the line of code that calls the method to check if someone has won.
Something like this:
private void button1_Click(object sender, EventArgs e)
{
int Player_Turn = Convert.ToInt32(player_turntxt.Text);
if (Player_Turn == 1)
{
button1.Text = "X";
player_turntxt.Text = "2";
button1.Enabled = false;
}
else
{
button1.Text = "O";
player_turntxt.Text = "1";
button1.Enabled = false;
}
CheckIfSomeoneHasWon();
}
Let's discuss the implementation of CheckIfSomeoneHasWon. I figure that there are several ways of doing it. We could create a bidimensional array with the values of the buttons, and iterate it. In fact, I will do it that way. Your way works too, but we would have to write a lot. This is what I came up with:
static readonly string _player1_symbol = "X";
static readonly string _player2_symbol = "O";
static void CheckIfSomeoneHasWon()
{
string[,] userChoices = BuildUserChoices();
string winner = CheckWhoWon(userChoices);
if (winner != null)
{
// Somebody won! Display message and start over
}
}
private static string CheckWhoWon(string[,] values)
{
// Horizontal checks
for (int i = 0; i < 3; i++)
{
if (values[i, 0] == values[i, 1] && values[i, 1] == values[i, 2])
{
return (values[i, 0] == _player1_symbol) ? "player 1" : "player 2";
}
}
// Vertical checks
for (int i = 0; i < 3; i++)
{
if (values[0, i] == values[1, i] && values[1,i] == values[2,i])
{
return (values[i, 0] == _player1_symbol) ? "player 1" : "player 2";
}
}
// Diagonal checks
if (values[0, 0] == values[1, 1] && values[1, 1] == values[2, 2])
{
return (values[0, 0] == _player1_symbol) ? "player 1" : "player 2";
}
if (values[0, 2] == values[1, 1] && values[1, 1] == values[2, 0])
{
return (values[1, 1] == _player1_symbol) ? "player 1" : "player 2";
}
// No one has won yet
return null;
}
private static string[,] BuildUserChoices()
{
var values = new string[3, 3];
values[0, 0] = button1.Text;
values[0, 1] = button2.Text;
values[0, 2] = button3.Text;
// and so on...
// If a button has not been click, they must have a unique text, like a number
return values;
}
You need to check if a player wins after each turn. Right now you are checking it once, after the form loaded.
I have used this code:
public static void write_excel(string[] str)
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
ObjExcel.Visible = false;
ObjExcel.UserControl = true;
ObjExcel.DisplayAlerts = false;
ObjWorkBook = ObjExcel.Workbooks.Open("C:\\Template_Modified.xls");
ObjWorkSheet = ObjWorkBook.Sheets[2];
ObjWorkSheet.Cells[4, 4] = str[0];
ObjWorkSheet.Cells[5, 4] = str[1];
ObjWorkSheet.Cells[6, 4] = str[2];
ObjWorkSheet.Cells[7, 4] = str[3];
ObjWorkBook.Save();
ObjExcel.Quit();
}
for (int i = 0; i < value1; i++)
{
TextBox tbx1 = (TextBox)(from t in this.Controls.OfType<TextBox>() where t.Name == i.ToString() select t).First();
str1 = tbx1.Text;
if (!string.IsNullOrWhiteSpace(str1))
{
arr5[i] = str1;
write_excel(arr5);
}
else
{
MessageBox.Show("Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
for (int i = val1; i < to_val1; i++)
{
TextBox tbx2 = (TextBox)(from t2 in this.Controls.OfType<TextBox>() where t2.Name == i.ToString() select t2).First();
str2 = tbx2.Text;
if (!string.IsNullOrWhiteSpace(str2))
{
arr1[i] = str2;
write_excel(arr1); // call the function (sent the array of strings)
}
else
{
MessageBox.Show("Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
How can I write the array of strings in the Excel file at the same time?
I have used TextBox from C# forms application.
After I have written the text in TextBox I have clicked OK button, and the text from TextBox is sent to the array of strings.
After the array of strings send the text to the function write_excel()
using System;
namespace excel_array_sent
{
class Program
{
static void Main(string[] args)
{
/* --------------------------------------------------------------------------------------------- */
string str = "DNO";
string str2 = "DNO";
string str3 = "DNO";
string str4 = "DNO";
string str5 = "DNO";
// Для получения значений равное 4
int value1_4 = 4;
int value2_4 = 8;
int value3_4 = 12;
int value4_4 = 16;
int value5_4 = 20;
string[] arr1_4 = new string[value1_4];
string[] arr2_4 = new string[value2_4];
string[] arr3_4 = new string[value3_4];
string[] arr4_4 = new string[value4_4];
string[] arr5_4 = new string[value5_4];
// Для получения значений равное 3
int value1_3 = 3;
int value2_3 = 7;
int value3_3 = 11;
int value4_3 = 15;
int value5_3 = 19;
string[] arr1_3 = new string[value1_3];
string[] arr2_3 = new string[value2_3];
string[] arr3_3 = new string[value3_3];
string[] arr4_3 = new string[value4_3];
string[] arr5_3 = new string[value5_3];
// Для получения значений равное 2
int value1_2 = 2;
int value2_2 = 6;
int value3_2 = 10;
int value4_2 = 14;
int value5_2 = 18;
string[] arr1_2 = new string[value1_2];
string[] arr2_2 = new string[value2_2];
string[] arr3_2 = new string[value3_2];
string[] arr4_2 = new string[value4_2];
string[] arr5_2 = new string[value5_2];
// Для получения значений равное 1
int value1_1 = 1;
int value2_1 = 5;
int value3_1 = 9;
int value4_1 = 13;
int value5_1 = 17;
string[] arr1_1 = new string[value1_1];
string[] arr2_1 = new string[value2_1];
string[] arr3_1 = new string[value3_1];
string[] arr4_1 = new string[value4_1];
string[] arr5_1 = new string[value5_1];
/* --------------------------------------------------------------------------------------------- */
for(int i = 0; i < value1_3; i++)
{
Console.Write(i.ToString() + "%");
arr1_4[i] = str;
write_excel(arr1_4);
}
for (int i = value1_4; i < value2_3; i++)
{
Console.Write(i.ToString() + "%");
arr2_4[i] = str2;
write_excel2(arr2_4);
}
for (int i = value2_4; i < value3_3; i++)
{
Console.Write(i.ToString() + "%");
arr3_4[i] = str3;
write_excel3(arr3_4);
}
}
public static void write_excel(string[] str)
{
try
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
ObjExcel.Visible = false;
ObjExcel.UserControl = true;
ObjExcel.DisplayAlerts = false;
ObjWorkBook = ObjExcel.Workbooks.Open("C:\\Шаблон.xls");
ObjWorkSheet = ObjWorkBook.Sheets[3];
int iNums = str.Length;
switch (iNums)
{
case 1:
{
ObjWorkSheet.Cells[4, 4] = str[0];
break;
}
case 2:
{
ObjWorkSheet.Cells[4, 4] = str[0];
ObjWorkSheet.Cells[5, 4] = str[1];
break;
}
case 3:
{
ObjWorkSheet.Cells[4, 4] = str[0];
ObjWorkSheet.Cells[5, 4] = str[1];
ObjWorkSheet.Cells[6, 4] = str[2];
break;
}
case 4:
{
ObjWorkSheet.Cells[4, 4] = str[0];
ObjWorkSheet.Cells[5, 4] = str[1];
ObjWorkSheet.Cells[6, 4] = str[2];
ObjWorkSheet.Cells[7, 4] = str[3];
break;
}
}
ObjWorkBook.SaveAs("C:\\Шаблон_Изменен.xls");
ObjExcel.Quit();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
public static void write_excel2(string[] str)
{
try
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
ObjExcel.Visible = false;
ObjExcel.UserControl = true;
ObjExcel.DisplayAlerts = false;
ObjWorkBook = ObjExcel.Workbooks.Open("C:\\Шаблон_Изменен.xls");
ObjWorkSheet = ObjWorkBook.Sheets[3];
int iNums = str.Length;
switch (iNums)
{
case 5:
{
ObjWorkSheet.Cells[8, 4] = str[4];
break;
}
case 6:
{
ObjWorkSheet.Cells[8, 4] = str[4];
ObjWorkSheet.Cells[9, 4] = str[5];
break;
}
case 7:
{
ObjWorkSheet.Cells[8, 4] = str[4];
ObjWorkSheet.Cells[9, 4] = str[5];
ObjWorkSheet.Cells[10, 4] = str[6];
break;
}
case 8:
{
ObjWorkSheet.Cells[8, 4] = str[4];
ObjWorkSheet.Cells[9, 4] = str[5];
ObjWorkSheet.Cells[10, 4] = str[6];
ObjWorkSheet.Cells[11, 4] = str[7];
break;
}
}
ObjWorkBook.Save();
ObjExcel.Quit();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
public static void write_excel3(string[] str)
{
try
{
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;
Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet;
ObjExcel.Visible = false;
ObjExcel.UserControl = true;
ObjExcel.DisplayAlerts = false;
ObjWorkBook = ObjExcel.Workbooks.Open("C:\\Шаблон_Изменен.xls");
ObjWorkSheet = ObjWorkBook.Sheets[3];
int iNums = str.Length;
switch (iNums)
{
case 9:
{
ObjWorkSheet.Cells[12, 4] = str[8];
break;
}
case 10:
{
ObjWorkSheet.Cells[12, 4] = str[8];
ObjWorkSheet.Cells[13, 4] = str[9];
break;
}
case 11:
{
ObjWorkSheet.Cells[12, 4] = str[8];
ObjWorkSheet.Cells[13, 4] = str[9];
ObjWorkSheet.Cells[14, 4] = str[10];
break;
}
case 12:
{
ObjWorkSheet.Cells[12, 4] = str[8];
ObjWorkSheet.Cells[13, 4] = str[9];
ObjWorkSheet.Cells[14, 4] = str[10];
ObjWorkSheet.Cells[15, 4] = str[11];
break;
}
}
ObjWorkBook.Save();
ObjExcel.Quit();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}
}
I have solved my problem (An example of a console application)
Well, I have a Form that receives the Employee's level and enable some options depending on his level using a bunch of Checkboxes. However the problem i am facing is that for my application's logic there is specific level range for every option to be enabled so i created an Ugly IF range checking statements that i am sure there is a better way to achieve.
CODE:
if (level >= 1 && level < 3) {
_items[0].Enabled = true;
_items[1].Enabled = false;
_items[2].Enabled = false;
_items[3].Enabled = false;
_items[4].Enabled = false;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 3 && level < 5) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = false;
_items[3].Enabled = false;
_items[4].Enabled = false;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 5 && level < 7) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = false;
_items[4].Enabled = false;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 7 && level < 9) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = true;
_items[4].Enabled = false;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 9 && level < 11) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = true;
_items[4].Enabled = true;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 11 && level < 13) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = true;
_items[4].Enabled = true;
_items[5].Enabled = true;
_items[6].Enabled = false;
_items[7].Enabled = false;
}
else if (level >= 13 && level < 15) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = true;
_items[4].Enabled = true;
_items[5].Enabled = true;
_items[6].Enabled = true;
_items[7].Enabled = false;
}
else if (level >= 15 && level < 17) {
_items[0].Enabled = true;
_items[1].Enabled = true;
_items[2].Enabled = true;
_items[3].Enabled = true;
_items[4].Enabled = true;
_items[5].Enabled = true;
_items[6].Enabled = true;
_items[7].Enabled = true;
}
You can simplify this with a little math:
int on = (level+1)/2;
for (int i = 0 ; i != 8 ; i++) {
_items[i].Enabled = (i < on);
}
The first line converts a number in the range from 1 to 16, inclusive, to a number in the range from 1 to 8, inclusive. Then the loop goes through all items, and enables as many of them as is indicated by the value of the on variable computed earlier.
You (might) lose performance, but its arguably more readable. Choose your poison! The performance difference depends on how often this is called.
if(level >= 1) {
_items[0].Enabled = level >= 1;
_items[1].Enabled = level >= 3;
_items[2].Enabled = level >= 5;
_items[3].Enabled = level >= 8;
_items[4].Enabled = level >= 9;
_items[5].Enabled = level >= 11;
_items[6].Enabled = level >= 13;
_items[7].Enabled = level >= 15;
}
One option, you could use a Dictionary to store the range for each checkbox-index:
private static Dictionary<int, Tuple<int, int>> _Ranges = new Dictionary<int, Tuple<int, int>>()
{
{ 0, Tuple.Create(1, 3) },{ 1, Tuple.Create(3, 5) },{ 2, Tuple.Create(5, 7) },{ 3, Tuple.Create(7, 9) },
{ 4, Tuple.Create(9, 11) },{ 5, Tuple.Create(11, 13) },{ 6, Tuple.Create(13, 15) },{ 7, Tuple.Create(15, 17) }
};
Now this concise code should do the same:
for(int i = 0; i <= 7; i++)
{
var range = _Ranges[i];
_items[i].Enabled = level >= range.Item1 && level < range.Item2;
}
You could also create a custom Range class which encapsulates this logic.
Turn it around to something like this instead:
_items[0].Enabled = ( level >= 1 && level < 17 );
....
Get rid of the elses:
_items[0].Enabled = false;
_items[1].Enabled = false;
_items[2].Enabled = false;
_items[3].Enabled = false;
_items[4].Enabled = false;
_items[5].Enabled = false;
_items[6].Enabled = false;
_items[7].Enabled = false;
if (level >= 1)
_items[0].Enabled = true;
if (level >= 3)
_items[1].Enabled = true;
if (level >= 5)
_items[2].Enabled = true;
if (level >= 7)
_items[3].Enabled = true;
if (level >= 9)
_items[4].Enabled = true;
if (level >= 11)
_items[5].Enabled = true;
if (level >= 13)
_items[6].Enabled = true;
if (level >= 15 && level < 17)
_items[7].Enabled = true;
Your security levels seem to be perfectly overlapping
So could you not do something as simple as
_items[0].Enabled = (level >= 1);
_items[1].Enabled = (level >= 3);
_items[2].Enabled = (level >= 5);
etc?
I would tend to suggest that this method of enabling / disabling the form components is flawed to begin with. And the top answer only solves this narrow case, where the items in the form are ordered and correspond 1 to N with the privilege levels...
If this application uses any kind of presentation separation scenario (MVC, MVVM, etc.) then this should certainly be done differently through databinding.
But even in the most naive case, a better way to handle this would be to add a privilege level flag to the checkboxes (maybe using their Tag in WinForms, an attached property in WPF, etc.) and loop through them comparing against the current privilege of the user. A dictionary of checkbox to privilege level would also work nicely:
Dictionary<Control, int> RequiredControlPrivilege;
foreach(var item in _items)
{
if(RequiredControlPrivilege.Contains(item)
{
item.Enabled = RequiredControlPrivilege[item] >= CurrentLevel
}
else
{
item.Enabled = false //Default to false or change to true...
}
}
I having trouble on combobox selectedindex. basically i wanted to disable the button1 when my textbox result is 1. but the problem is when the button1 get disable and i chose another option it wont enable back. so is there another way to do it? below is just showing some part of the coding.
double[,] arr;
public Form1()
{
arr = new double[3, 3];
for (int i = 0; i < 2; i++)
{
arr[0, 0] = 1;
arr[0, 1] = 0.79;
arr[0, 2] = 1.17;
arr[1, 0] = 1.26;
arr[1, 1] = 1;
arr[1, 2] = 1.08;
arr[2, 0] = 0.85;
arr[2, 1] = 0.93;
arr[2, 2] = 1;
}
void CreateArray()
{
if (comboBox1.SelectedIndex == -1 || comboBox2.SelectedIndex == -1)
return;
else if (comboBox1.SelectedIndex == 1 || comboBox2.SelectedIndex == 0)
{
button1.Enabled = false;
}
else if (comboBox1.SelectedIndex == 0 || comboBox2.SelectedIndex == 1)
{
button1.Enabled = false;
}
else if (comboBox1.SelectedIndex == 1 || comboBox2.SelectedIndex == 2)
{
button1.Enabled = false;
}
else
{
button1.Enabled = true;
}
If the second combobox has only 3 items then you will never be able to reach the final else clause where you reset the button to the enabled state.
This happens because you use the || logical OR operator and with only three items you will always take one of the else if condition before the final else