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.
Related
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.
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);
}
}
}
}
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).
i have a code like this:
Label[,] Cell = new Label[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
Cell[i, j] = new Label();
Cell[i, j].Text = (i + 1) + "" + (j + 1);
Cell[i, j].Location = new Point(j * 50 + 25, i * 50 + 25);
this.Controls.Add(Cell[i, j]);
Cell[i, j].Click += new System.EventHandler(lbl_click);
}
}
public void lbl_click(object sender, EventArgs e)
{
//I want having i & j here and work with them.
}
How can I access i and j variables from within the click event handler?
Using the Tag property
One option could be to Tag the label with the data you need to use.
For example, create a class to hold the data...
class TagData
{
public int I { get; set; }
public int J { get; set; }
}
In your loop...
Cell[i, j].Tag = new TagData() { I = i, J = j };
In the event handler...
public void lbl_click(object sender, EventArgs e)
{
Label label = sender as Label;
TagData tagData = label.Tag as TagData;
// Do something with tagData.I and tagData.J
}
Parsing the label Text
If you can assume that neither i or j would be more than a single digit each, then you could simply parse the Text. Like so:
public void lbl_click(object sender, EventArgs e)
{
Label label = sender as Label;
int i = int.Parse(label.Text[0]) - 1;
int j = int.Parse(label.Text[1]) - 1;
}
NOTE: The danger with more than a single digit for each is that without a separator you could not know if "123" was i = 1 or i = 12. You could of course work around this by using a separator, for example "12,3" but I wouldn't suggest having code that relies on specific UI design/formatting.
Ok thanks to musefan here is the solution with storing the coordinates in the Tag of the label. Winforms controls got a Property called Tag where you can store related Information.
Label[,] Cell = new Label[8, 8];
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
Label tempLabel = new Label();
Cell[i,j] = tempLabel;
tempLabel.Text = (i + 1) + "" + (j + 1);
tempLabel.Location = new Point(j * 50 + 25, i * 50 + 25);
tempLabel.Click += new System.EventHandler(lbl_click);
tempLabel.Tag = new Tuple<int, int>(i, j);
this.Controls.Add(tempLabel);
}
}
public void lbl_click(object sender, EventArgs e)
{
Label label = sender as Label;
Tuple<int, int> position = label.Tag as Tuple<int, int>;
if(positon != null)
{
int i = position.Item1;
int j = position.Item2;
//do whatever with the coordinates
}
}
Hello everyone I need some help with the positioning of an array of buttons.I want to make this function so it scans the name of the previous button and it names the next one +1,afterwards I want to position these buttons on the screen having a certain space between them and them being positioned in the center of the screen.I have tried many times to modify my method but I don't know how to get this method to work.
This is how my method looks like.
UPDATED
PS.Reference not set to an instance of an object Q.Q
public Button[] ButtonCreator(byte numOfBtnsNeeded,Form1 form)
{
Button[] mybtns = new Button[numOfBtnsNeeded];
foreach (Button b in mybtns)
{
for (int i = 0; i < mybtns.Length; i++)
{
mybtns[i].Name = i.ToString();
mybtns[i].Parent = form;
mybtns[i].Height = 50;
mybtns[i].Width = 50;
for (int k = i + 1; k < mybtns.Length; k++)
{
mybtns[i].Location = new Point(190, 80);
mybtns[k].Location = Point.Add(new Point(mybtns[i].Location.X + 10,mybtns[i].Location.Y + 10),new Size(mybtns[i].Size.Width,mybtns[i].Size.Height));
}
}
}
foreach (Button b in mybtns)
{
b.Show();
}
return mybtns;
}
Play with this example...
public partial class Form1 : Form
{
private List<List<Button>> grid = new List<List<Button>>();
public Form1()
{
InitializeComponent();
byte numRows = 5;
byte numCols = 5;
for (byte i = 0; i < numRows; i++)
{
grid.Add(ButtonRowCreator(numCols, 25, (i+1) * 50));
}
}
public List<Button> ButtonRowCreator(byte numOfBtnsNeeded, int x, int y)
{
List<Button> btns = new List<Button>();
for (int i = 0; i < numOfBtnsNeeded; i++)
{
Button btn = new Button();
btn.Size = new Size(50, 50);
btn.Location = new Point(x + (i * btn.Width), y);
btns.Add(btn);
this.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
return btns;
}
void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
btn.Text = "X";
int curRow = -1, curCol = -1;
for(int i = 0; i < grid.Count; i++)
{
int index = grid[i].IndexOf(btn);
if (index != -1)
{
curRow = i;
curCol = index;
Console.WriteLine("curRow = " + curRow.ToString() + ", curCol = " + curCol.ToString());
}
}
// ... now you can use "curRow", "curCol" and "grid" to do something ...
// reset all BackColors:
foreach (List<Button> row in grid)
{
foreach (Button col in row)
{
col.BackColor = Button.DefaultBackColor;
}
}
// the below should give you some examples for the
// syntax necessary to access buttons in the grid
// highlight current row:
foreach (Button col in grid[curRow])
{
col.BackColor = Color.Yellow;
}
// highlight current col:
for (int i = 0; i < grid.Count; i++)
{
grid[i][curCol].BackColor = Color.Yellow;
}
}
}
You cannot change a foreach variable reference (ie b). If you want to initialize an array you should use for loop:
for(int i = 0; i < numOfBtnsNeeded; i++)
{
var button = mybtns[i] = new Button();
//Here you can modify the reference of button.
}
Also, mybtns will be full of nulls since Button is a reference type which means it's default value is a null.
you want something like:
public Button[] ButtonCreator(byte numOfBtnsNeeded)
{
Button[] mybtns = new Button[numOfBtnsNeeded];
for (int i = 0; i < mybtns.Length; i++)
{
mybtns[i] = new Button();
mybtns[i].Name = (i + 1).ToString();
}
return mybtns;
}
I'm not sure why you're using a byte over an int, but it works either way.
Essentially, when you create the array, you're not creating the objects within the array. And you cannot modify the thing you are looping over within a foreach loop, so you need a for loop.