check the condition and remove dynamic controls accordingly c# - c#

I have a combobox which has values 4-9, and according to that value I want generate runtime labels and textboxes. When I click on 6 then the code can generate 6 labels and textboxes as required, but when I click on 5 again one label and textbox should disappear or if I click on 4 again 2 labels and textboxes should disappear....which is not happening. I have this code in c#. What changes should I make in this code? Is there any other way that I can do this code?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Text == "4")
{
checkBox1.Visible = true;
for (int i = 0; i < 4; i++)
{
addlabel(i);
}
for (int i1 = 0; i1 < 4; i1++)
{
addlabel1(i1);
}
}
if (comboBox1.Text == "5")
{
checkBox1.Visible = true;
for (int i = 0; i < 5; i++)
{
addlabel(i);
}
for (int i1 = 0; i1 < 5; i1++)
{
addlabel1(i1);
}
}
if (comboBox1.Text == "6")
{
checkBox1.Visible = true;
for (int i = 0; i < 6; i++)
{
addlabel(i);
}
for (int i1 = 0; i1 < 6; i1++)
{
addlabel1(i1);
}
}
}
void addlabel(int i)
{
int left = 70;
int top = 100;
int step_x = 80;
int step_y = 30;
new Label()
{
Name = $"label{i}",
Text = "Enter Subject:",
Location = new Point(left, top + step_y * i),
Parent = this,
};
left += step_x;
int left1 = 357;
int top1 = 100;
int step_x1 = 80;
int step_y1 = 30;
new Label()
{
Name = $"label{i}",
Text = "Total Marks:",
Location = new Point(left1, top1 + step_y1 * i),
Parent = this,
};
left1 += step_x1;
}
void addlabel1(int i1)
{
int left = 200;
int top = 100;
int step_x = 80;
int step_y = 30;
new TextBox()
{
Name = $"textbox{i1}",
Text = "",
Size = new Size(122, 20),
Location = new Point(left, top + step_y * i1),
Parent = this,
};
left += step_x;
int left1 = 480;
int top1 = 100;
int step_x1 = 80;
int step_y1 = 30;
new TextBox()
{
Name = $"textbox{i1}",
Text = "",
Size = new Size(122, 20),
Location = new Point(left1, top1 + step_y1 * i1),
Parent = this,
};
left1 += step_x1;
}
Any Suggestions? Help me out.

Try the following code:
public partial class Form1 : Form
{
private int prev = 0;
private Point lblLocation = new Point(70, 100);
private Point tbLocation = new Point(170, 100);
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int cur = Convert.ToInt32(comboBox1.SelectedItem);
int tmp = cur - prev;
if (tmp > 0)
{
// add new controls
for (int i = 1; i <= tmp; i++)
{
AddLabel(prev + i);
AddTextBox(prev + i);
lblLocation.Y += 30;
tbLocation.Y += 30;
}
prev = cur;
}
else
{
// remove controls
tmp = Math.Abs(tmp);
for(int i= 0; i < tmp; i++)
{
RemoveControl($"lbl{prev}");
RemoveControl($"tb{prev}");
lblLocation.Y -= 30;
tbLocation.Y -= 30;
prev--;
}
}
}
private void AddLabel(int i)
{
new Label()
{
Name = $"lbl{i}",
Text = $"lbl{i}",
Location = lblLocation,
Parent = this
};
}
private void AddTextBox(int i)
{
new TextBox()
{
Name = $"tb{i}",
Text = $"tb{i}",
Location = tbLocation,
Parent = this
};
}
private void RemoveControl(string name)
{
foreach (Control item in Controls.OfType<Control>())
{
if (item.Name == name)
{
Controls.Remove(item);
}
}
}
}

Related

trouble with displaying ships names when they are sunk

the problem i'm facing right now is that i don't know how to check on the opponent's move which ships it sinks so i can display a message saying "Your ____ has sunk".
this is the code i have written
namespace Naval
{
public partial class Form2 : Form
{
const int Size_grid = 10;
const int picturebox = 50;
PictureBox[,] playerBoard = new PictureBox[Size_grid, Size_grid];
PictureBox[,] opponentBoard = new PictureBox[Size_grid, Size_grid];
int[,] playerShips = new int[Size_grid, Size_grid];
int[,] opponentShips = new int[Size_grid, Size_grid];
int[] Lengths = new int[] { 5, 4, 3, 2 };
//string[] Names = new string[] { "Αεροπλανοφόρο", "Αντιτορπιλικό", "Πολεμικό", "Υποβρύχιο" };
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox playerPictureBox = new PictureBox();
playerPictureBox.Size = new Size(picturebox, picturebox);
playerPictureBox.Location = new Point(col * (picturebox + 10) + 185, row * (picturebox + 10) + 245);
playerPictureBox.Click += PictureBox_Click;
playerPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
playerPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(playerPictureBox);
playerBoard[row, col] = playerPictureBox;
}
}
for (int row = 0; row < Size_grid; row++)
{
for (int col = 0; col < Size_grid; col++)
{
PictureBox opponentPictureBox = new PictureBox();
opponentPictureBox.Size = new Size(picturebox, picturebox);
opponentPictureBox.Location = new Point(col * (picturebox + 10) + 1145, row * (picturebox + 10) + 245);
opponentPictureBox.Click += PictureBox_Click;
opponentPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
opponentPictureBox.BackColor = Color.Gray;
panel1.Controls.Add(opponentPictureBox);
opponentBoard[row, col] = opponentPictureBox;
}
}
PlacePlayerShips(playerShips, Lengths);
PlaceOpponentShips(opponentShips, Lengths);
}
private void PictureBox_Click(object sender, EventArgs e)
{
PictureBox pictureBox = (PictureBox)sender;
int row = (pictureBox.Location.Y - 245) / (picturebox + 10);
int col = (pictureBox.Location.X - 1145) / (picturebox + 10);
if (pictureBox.Location.X >= 1145 && pictureBox.ImageLocation == null) // opponent board
{
if (row >= 0 && row < opponentShips.GetLength(0) && col >= 0 && col < opponentShips.GetLength(1))
{
if (opponentShips[row, col] > 0)
{
pictureBox.ImageLocation = "x.png";
}
else
{
pictureBox.ImageLocation = "-.png";
}
ComputerMove();
}
}
}
private void ComputerMove()
{
Random random = new Random();
int row = random.Next(Size_grid);
int col = random.Next(Size_grid);
while (playerBoard[row, col].ImageLocation != null)
{
row = random.Next(Size_grid);
col = random.Next(Size_grid);
}
if (playerShips[row, col] > 0)
{
playerBoard[row, col].ImageLocation = "x.png";
}
else
{
playerBoard[row, col].ImageLocation = "-.png";
}
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void PlacePlayerShips(int[,] playerShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row, col + i] = 1;
playerBoard[row, col + i].BackColor = Color.LightBlue;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (playerShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
playerShips[row + i, col] = 1;
playerBoard[row + i, col].BackColor = Color.LightBlue;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void PlaceOpponentShips(int[,] opponentShips, int[] shipLengths)
{
Random random = new Random(DateTime.Now.Millisecond);
;
foreach (int shipLength in shipLengths)
{
int row, col;
int direction = random.Next(2);
int placed = 0;
while (placed == 0)
{
if (direction == 0) // Horizontal
{
row = random.Next(Size_grid);
col = random.Next(Size_grid - shipLength + 1);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row, col + i] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row, col + i] = 1;
}
}
}
else // Vertical
{
row = random.Next(Size_grid - shipLength + 1);
col = random.Next(Size_grid);
// Check if ship overlaps with other ships
int overlap = 0;
for (int i = 0; i < shipLength; i++)
{
if (opponentShips[row + i, col] == 1)
{
overlap = 1;
}
}
// Place ship if no overlap
if (overlap == 0)
{
placed = 1;
for (int i = 0; i < shipLength; i++)
{
opponentShips[row + i, col] = 1;
}
}
}
// Change direction if ship couldn't be placed
if (placed == 0)
{
direction = (direction + 1) % 2;
}
}
}
}
private void label1_Click(object sender, EventArgs e)
{
}
int time = 0;
private void timer1_Tick(object sender, EventArgs e)
{
time++;
label42.Text= time.ToString();
}
private void timer2_Tick(object sender, EventArgs e)
{
label44.Text = " ";
timer2.Enabled = false;
}
}
}
i tried adding a switch with choices 1-4 but it didn't work i've also tried having a int[] ship Hits = new int[] {0,0,0,0} and just adding 1 every time a ship was hit but that didn't go as planned because i didn't know how to bind each item of the array to a ship . and i think that's about it
One approach that you might find helpful would be to bundle up all the information about a Ship into a class. This is an abstraction that could make it easier for displaying ship names when they are sunk. At the same time, use inheritance so that a Ship is still a PictureBox with all the functionality that implies.
Ship minimal class example
Member properties tell us what we need know about a ship. Use enum values to make the intent perfectly clear.
class Ship : PictureBox
{
#region P R O P E R T I E S
[Description("Type")]
public τύπος τύπος
{
get => _τύπος;
set
{
if (!Equals(_τύπος, value))
{
_τύπος = value;
switch (_τύπος)
{
case τύπος.Αεροπλανοφόρο: Image = Image.FromFile(Path.Combine(_imageDir, "aircraft-carrier.png")); break;
case τύπος.Αντιτορπιλικό: Image = Image.FromFile(Path.Combine(_imageDir, "destroyer.png")); break;
case τύπος.Πολεμικό: Image = Image.FromFile(Path.Combine(_imageDir, "military.png")); break;
case τύπος.Υποβρύχιο: Image = Image.FromFile(Path.Combine(_imageDir, "submarine.png")); break;
}
}
}
}
τύπος _τύπος = 0;
public bool Sunk { get; set; }
[Description("Flag")]
public σημαία σημαία
{
get => _σημαία;
set
{
_σημαία = value;
onUpdateColor();
}
}
σημαία _σημαία = σημαία.Player;
#endregion P R O P E R T I E S
private void onUpdateColor()
{
var color =
Sunk ? Color.Red :
σημαία.Equals(σημαία.Player) ?
Color.Navy :
Color.DarkOliveGreen;
for (int x = 0; x < Image.Width; x++) for (int y = 0; y < Image.Height; y++)
{
Bitmap bitmap = (Bitmap)Image;
if (bitmap.GetPixel(x, y).R < 0x80)
{
bitmap.SetPixel(x, y, color);
}
}
Refresh();
}
public Point[] Hits { get; set; } = new Point[0];
public override string ToString() =>
$"{σημαία} {τύπος} # {((TableLayoutPanel)Parent)?.GetCellPosition(this)}";
private readonly static string _imageDir =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
}
Where enum values are:
enum Direction
{
Horizontal,
Vertical,
}
enum τύπος
{
[Description("Aircraft Carrier")]
Αεροπλανοφόρο = 5,
[Description("Destroyer")]
Αντιτορπιλικό = 4,
[Description("Military")]
Πολεμικό = 3,
[Description("Submarine")]
Υποβρύχιο = 2,
}
/// <summary>
/// Flag
/// </summary>
enum σημαία
{
Player,
Opponent,
}
Displaying ships names when they are sunk
When the inherited Ship version of PictureBox is clicked the information is now available.
private void onAnyShipClick(object sender, EventArgs e)
{
if (sender is Ship ship)
{
MessageBox.Show(ship.ToString());
}
}
Images credit: Robuart
Used under license.

Copying values from dynamic textbox to jagged array error

How can I copy the values from dynamic textboxes to a jagged array? I tried with a for cycle but I constantly get this error message:"Object reference not set to an instance of an object." What can be the problem?(the textboxes are also made with jagged arrays) Here is the full code, you can find the problematic lines in the first lines of the button1 event handler link
for (int a = 0; a < nr; a++)
{
for (int b = 0; b < nr+ 1; b++)
{
array[a][b] =int.Parse(TB[a][b].Text);
}
}
(Here's the full code:)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
int ismeretlen = 2;
TextBox[][] TB;
string file = "3ismeretlen.dat";
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int[][] egyenletek = new int[ismeretlen][];
for (int a = 0; a < ismeretlen; a++)
{
for (int b = 0; b < ismeretlen + 1; b++)
{
egyenletek[a][b] =int.Parse(TB[a][b].Text);
}
}
int változószám = TB[0].Length;
for (int i = 0; i < változószám - 1; i++)
{
for (int j = i; j < változószám - 1; j++)
{
int[] d = new int[változószám];
for (int x = 0; x < változószám; x++)
{
if (i == j && egyenletek[j][i] == 0)
{
bool changed = false;
for (int z = egyenletek.Length - 1; z > i; z--)
{
if (egyenletek[z][i] != 0)
{
int[] temp = new int[változószám];
temp = egyenletek[z];
egyenletek[z] = egyenletek[j];
egyenletek[j] = temp;
changed = true;
}
}
if (!changed)
{
textBox1.Text += "Az egyenletrendszernek nincs megoldása!\r\n";
return;
}
}
if (egyenletek[j][i] != 0)
{
d[x] = egyenletek[j][x] / egyenletek[j][i];
}
else
{
d[x] = egyenletek[j][x];
}
}
egyenletek[j] = d;
}
for (int y = i + 1; y < egyenletek.Length; y++)
{
int[] f = new int[változószám];
for (int g = 0; g < változószám; g++)
{
if (egyenletek[y][i] != 0)
{
f[g] = egyenletek[y][g] - egyenletek[i][g];
}
else
{
f[g] = egyenletek[y][g];
}
}
egyenletek[y] = f;
}
}
double val = 0;
int k = változószám - 2;
double[] eredmény = new double[egyenletek.Length];
for (int i = egyenletek.Length - 1; i >= 0; i--)
{
val = egyenletek[i][változószám - 1];
for (int x = változószám - 2; x > k; x--)
{
val -= egyenletek[i][x] * eredmény[x];
}
eredmény[i] = val / egyenletek[i][i];
if (eredmény[i].ToString() == "NaN" || eredmény[i].ToString().Contains("Végtelen sok megoldás."))
{
textBox1.Text += "Az egyenletrendszernek nincs megoldása!\n";
return;
}
k--;
TextBox[] megoldás = new TextBox[ismeretlen];
for (int b = 0; b < ismeretlen; i++)
{
megoldás[b] = new TextBox();
megoldás[b].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
megoldás[b].Left = 536+ b * 36;
megoldás[b].Top = 36 * b + 10;
megoldás[b].Width = 35;
megoldás[b].Font = new Font(megoldás[b].Font.FontFamily, 16);
megoldás[b].BackColor = Color.Cyan;
megoldás[b].TextAlign = HorizontalAlignment.Center;
megoldás[b].Text = eredmény[ismeretlen - 1].ToString();
this.panel1.Controls.Add(megoldás[b]);
}
FileStream fs = new FileStream(file, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
for (int r = 0; r < ismeretlen; r++)
for (int t = 0; t < ismeretlen + 1; t++)
bw.Write(egyenletek[r][t]);
bw.Close();
fs.Close();
}
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
numericUpDown1.Maximum = 6;
numericUpDown1.Minimum = 2;
}
private void Generál_Click(object sender, EventArgs e)
{
this.panel1.Controls.Clear();
ismeretlen = (int)numericUpDown1.Value;
TB = new TextBox[ismeretlen][];
for(int i = 0; i < ismeretlen; i++)
TB[i] = new TextBox[ismeretlen + 1];
int height = 20;
int width = 40;
int curX = 10;
int curY = 10;
for(int i = 0; i < ismeretlen; i++)
{
for(int j = 0; j < ismeretlen + 1; j++)
{
TextBox txtbox = new TextBox();
txtbox = new TextBox();
txtbox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
txtbox.Left = curX;
txtbox.Top = curY;
txtbox.Width = width;
txtbox.Height = height;
txtbox.Font = new Font(txtbox.Font.FontFamily, 16);
txtbox.BackColor = Color.Azure;
txtbox.TextAlign = HorizontalAlignment.Center;
TB[i][j] = txtbox;
this.panel1.Controls.Add(TB[i][j]); // Add as a child of panel
curX += width + 15;
}
curX = 10;
curY = curY + height + 20;
}
}
private void Ment_Click(object sender, EventArgs e)
{
}
}
}
In this line of code, you only initialize the first dimension of your array:
int[][] egyenletek = new int[ismeretlen][];
But you then use it before initializing the second dimension a handful of lines later (so this dimension is null (an object not set to a reference)):
egyenletek[a][b] =int.Parse(TB[a][b].Text);
Before that line, you should initialize the 2nd dimension in some way. You did this at another part of your code, in the lines of 172-173 in your jsfiddle link.
In general, when you see this error you should evaluate what objects you are reading from and assigning to and ensure they have been initialized (ie. they are not null).

How to interact with variables (just created in the program) that are in another method?

In the first method I'm creating a matrix of textboxes and in another (Button_click) method. I need to take the values of textboxes from the Button_Click method and then do something with them. I don't know how interact with just created values(the names are also new). But I know that I can't use t[j].
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex+2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
TextBox[] t = new TextBox[selectedIndex];
for (int j = 0; j < selectedIndex; j++)
{
t[j] = new TextBox();
t[j].Name = "a" + (i + 1) + (j + 1);
t[j].Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(t[j]);
Thickness m = t[j].Margin;
m.Left = 1;
m.Bottom = 1;
t[j].Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
t[j].InputScope = scope;
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Double sa11v = Convert.ToDouble(t[j].Text);
}
Sorry for my English, I'm from Russia :)
you could create a member variable that is used outside the event in which you have created TextBox Array-
TextBox[] _t = null;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex + 2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
_t = new TextBox[selectedIndex];
for (int j = 0; j < selectedIndex; j++)
{
_t[j] = new TextBox();
_t[j].Name = "a" + (i + 1) + (j + 1);
_t[j].Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(_t[j]);
Thickness m = t[j].Margin;
m.Left = 1;
m.Bottom = 1;
_t[j].Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
_t[j].InputScope = scope;
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_t != null)
{
//Do your work here
// Double sa11v = Convert.ToDouble(t[j].Text);
}
}
but for a broader aspect, you can use dictionary,
Dictionary<string, TextBox> _dicTextBoxes;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int selectedIndex = vsematrici.SelectedIndex + 2;
StackPanel[] v = new StackPanel[selectedIndex];
for (int i = 0; i < selectedIndex; i++)
{
v[i] = new StackPanel();
v[i].Name = "matrixpanel" + i;
v[i].Orientation = Orientation.Horizontal;
_dicTextBoxes = new Dictionary<string, TextBox>();
for (int j = 0; j < selectedIndex; j++)
{
TextBox txtBox = new TextBox();
txtBox = new TextBox();
txtBox.Name = "a" + (i + 1) + (j + 1);
txtBox.Text = "a" + (i + 1) + (j + 1);
v[i].Children.Add(txtBox);
Thickness m = txtBox.Margin;
m.Left = 1;
m.Bottom = 1;
txtBox.Margin = m;
InputScope scope = new InputScope();
InputScopeName name = new InputScopeName();
name.NameValue = InputScopeNameValue.TelephoneNumber;
scope.Names.Add(name);
txtBox.InputScope = scope;
_dicTextBoxes.Add(txtBox.Name, txtBox);
}
mainpanel.Children.Add(v[i]);
}
Button button1 = new Button();
button1.Content = "Найти определитель";
button1.Click += Button_Click;
mainpanel.Children.Add(button1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_dicTextBoxes != null)
{
// a23 is the name of textbox, 'a' is prefixe, '2' is the 2nd stackpanel you have added
// '3' is the 3rd textbox you have added in stackpanel
if (_dicTextBoxes.ContainsKey("a23"))
{
//Do your work here
Double sa11v = Convert.ToDouble(_dicTextBoxes["a23"].Text);
}
}
}
Loop through the Children of mainpanel and check each control if it is a TextBox. Something like:
foreach (UIElement ctrl in mainpanel.Children)
{
if (ctrl.GetType() == typeof(TextBox))
{
TextBox oneOfYourTextBoxes = ((TextBox)ctrl);
// do your thing
}
}
You cannot change an arrays size after you created it. Hence your size is known only at runtime after firing your event you cannot set its size within the declaration.
class MyClass
{
Textbox[] myTextBoxes;
private void vsematrici_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ...
myTextBoxes = new TextBoxes[selectedIndex];
}
private void Button_Click(object sender, RoutedEventArgs e)
{
int myIndex = // your selected item here
if (this.myTextBoxes != null && myIndex < this.myTextBoxes.Length)
{
Console.WriteLine(this.myTextBoxes[myIndex].Text);
}
}
}
This will also work:
button1.Click += (sender, args) => DoSomethingToTextboxes(_t);

Where is the position number at

I am trying to create a chess board strategy application in WinForms c#.
Someone from here was gracious enough to help with this code.
When it is run, it does everything I wanted except that the sq.position values are wrong.
The value like A1 should be A7, A6 should be A2
How can I reverse the order of the number value in this code:
private void Test_Load(object sender, EventArgs e)
{
int blockSize = 70;
Panel[,] chessBoardPanels = new Panel[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j > 8; j++)
{
ChessSquare sq = new ChessSquare(((char)(65 + i)).ToString(), j);
sq.Color = (i + (j % 2)) % 2 == 0 ? Color.Black : Color.White;
Panel p = new Panel()
{
Size = new Size(blockSize, blockSize),
BackColor = sq.Color,
Tag = sq,
Location = new Point(blockSize * i + 15, blockSize * j + 15)
};
p.MouseEnter += new EventHandler(squareMouseEnter);
p.MouseLeave += new EventHandler(squareMouseLeave);
chessBoardPanels[i, j] = p;
groupBox1.Controls.Add(p);
}
}
}
private void squareMouseLeave(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = sq.Color;
}
private void squareMouseEnter(object sender, EventArgs e)
{
Panel p = (Panel)sender;
ChessSquare sq = (ChessSquare)p.Tag;
p.BackColor = Color.Aqua;
label1.Text = string.Format("Current position: {0}", sq.Position);
}
public class ChessSquare
{
public string Letter { get; set; }
public int Number { get; set; }
public Color Color { get; set; }
public string Position
{
get { return string.Format("{0}{1}", Letter, Number + 1); }
}
public ChessSquare()
{ }
public ChessSquare(string letter, int number)
{
Letter = letter;
Number = number;
}
}
I am still very new to this type of programming....
Change this:
ChessSquare sq = new ChessSquare(((char)(65 + i)).ToString(), j);
to that:
ChessSquare sq = new ChessSquare(((char)(65 + i)).ToString(), 7 - j);
Update: Corrected! Thanks user2772713!

How to copy values from textbox into array of labels?

OK Here's what I did and the values which were set vertical are copied in the labels but horizontal. And only one column/row.
public partial class Form1 : Form
{
private Label l;
private Button bStart;
private TextBox txtVnes;
private Label[] pole;
public Form1()
{
InitializeComponent();
bStart = new Button();
bStart.Location = new Point(240, 165);
bStart.Width = 75;
bStart.Height = 25;
bStart.Text = "START";
txtVnes = new TextBox();
txtVnes.Location = new Point(240, 10);
txtVnes.Width = 160;
txtVnes.Height = 130;
txtVnes.Multiline = true;
int a = 0;
pole = new Label[42];
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 7; j++)
{
l = new Label();
l.Name = "label" + i.ToString() + j.ToString();
l.Text = "Z";
l.Width = 20;
l.Height = 20;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Parent = this;
l.BackColor = Color.FromArgb(100, 149, 237);
l.Location = new Point(10 + (j - 1) * 25, 15 + (i - 1) * 25);
pole[a] = l;
this.Controls.Add(l);
a++;
}
}
this.Controls.Add(bStart);
this.Controls.Add(txtVnes);
bStart.Click += new EventHandler(bStart_Click);
}
private void bStart_Click(object sender, EventArgs e)
{
Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
bool isValid = true;
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
if (ts == null || ts.Length < 1 || ts.Length > 6)
{
MessageBox.Show("Not valid");
}
else
{
foreach (string t in ts)
{
if (regex.IsMatch(t) == false)
{
MessageBox.Show("Not valid");
break;
}
}
}
if (isValid)
{
for (int i = 0; i < 6; i++)
{
if (i < ts.Length && regex.IsMatch(ts[i]))
{
pole[i].Text = ts[i];
}
else
{
pole[i].Text = "not valid";
}
}
}
}
Here's a photo
So here is the problem: When I click on the button bStart only one value is copied and replaced in one labe from the array of labels.
This should work like this: After the user clicks on the button bStart, all values from the textbox txtVnes should be copied in each label in the array of labels. All the labels have text "Z", and after click on the button they should be changed with the values in the textbox txtVnes. As you can see i used l.Text = txtVnes.Text; to copy the values, but it doesn't work. I appreciate if you can help me, thank you!
You are always setting the text of the same label l. Since your labels are in the array pole, you should set the text to consecutive pole indices.
I you want all the valid texts at the beginning:
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
int k = 0;
for (int i = 0; i < ts.Length && k < 6; i++) {
if (IsValid(ts[i])) { // Where IsValid is a method containing your validation logic.
pole[k++].Text = ts[i];
}
}
// Fill remaining labels
for (int i = k; i < 6; i++) {
pole[i].Text = "not valid";
}
Or, if you want vaild and invalid texts mixed:
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < 6; i++) {
if (i < ts.Length && IsValid(ts[i])) { // Where IsValid is a method containing your validation logic.
pole[i].Text = ts[i];
} else {
pole[i].Text = "not valid";
}
}
Note that array indices begin at 0, not at 1.
EDIT #2:
The IsValid method would look like this:
private static Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
private static bool IsValid(string s)
{
return regex.IsMatch(s);
}
To answer your question in the comment: Yes, my examples above have to be placed in bStart_Click.
And there is also another error in your form constructor. this.Controls.Add(l); should be placed inside the inner for-loop, just after pole[a] = l;, otherwise only one label will be visible on your form.
Finally after having implemented and anlyzed your code, I came to the conclusion that you want to be able to enter text in the following format into the textbox and then place the digits into corresponding labels:
1 2 3 4 5 6 7
2 3 4 6 7 8 0
0 1 2 6 6 6 7
1 2 3 4 5 6 7
2 3 4 6 7 8 0
0 1 2 6 6 6 7
The complete code should look like this:
public partial class Form1 : Form
{
private Button bStart;
private TextBox txtVnes;
private Label[] pole;
public Form1()
{
InitializeComponent();
bStart = new Button();
bStart.Location = new Point(240, 165);
bStart.Width = 75;
bStart.Height = 25;
bStart.Text = "START";
bStart.Click += new EventHandler(bStart_Click);
this.Controls.Add(bStart);
txtVnes = new TextBox();
txtVnes.Location = new Point(240, 10);
txtVnes.Width = 160;
txtVnes.Height = 130;
txtVnes.Multiline = true;
this.Controls.Add(txtVnes);
int a = 0;
pole = new Label[42];
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 7; j++) {
var l = new Label();
l.Name = "label" + i.ToString() + j.ToString();
l.Text = "Z";
l.Width = 20;
l.Height = 20;
l.TextAlign = ContentAlignment.MiddleCenter;
l.Parent = this;
l.BackColor = Color.FromArgb(100, 149, 237);
l.Location = new Point(10 + (j - 1) * 25, 15 + (i - 1) * 25);
pole[a] = l;
this.Controls.Add(l);
a++;
}
}
}
private void bStart_Click(object sender, EventArgs e)
{
string[] ts = txtVnes.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
int row = 0;
for (int i = 0; i < ts.Length && row < 6; i++) {
if (LineIsValid(ts[i])) {
for (int col = 0; col < 7; col++) {
pole[row * 7 + col].Text = ts[i][2 * col].ToString();
}
row++;
}
}
// Fill remaining labels
for (; row < 6; row++) {
for (int col = 0; col < 7; col++) {
pole[row * 7 + col].Text = "Z";
}
}
}
private static Regex regex = new Regex(#"^(\s)*(\d ){6}\d(\s)*$");
private static bool LineIsValid(string line)
{
return regex.IsMatch(line);
}
}
Two nested loops are required in bStart_Click as well. One for the rows and one for the columns.

Categories

Resources