I am trying to find a way to determine the Index of the first character in a specific Line in RichEditBox (UWP)
in Richtextbox was easy
int indx1stlinchr = myRichTextBox.GetFirstCharIndexFromLine(i);
is there a way to do that or a workaround method ?
a part from my coloring method in Winforms Richtextbox
public void colorTheText(string rohtext)
{
myRichTextBox.SelectionLength = 0;
int def = network.SubSop_Deff;
var line = Regex.Split(rohtext, "\n|\r|\n\n");
int ipclassRange = CColor.KlassebitsRange(network.Network_Class, network.Netmask_length);
int k = 1;
int l = 1;
for (int i = 0; i < line.Length; i++)
{
int indx1stlinchr = myRichTextBox.GetFirstCharIndexFromLine(i);
int indexlinedge = line[i].LastIndexOf(" ");
if (line[i].StartsWith(">Network") == true)
{
myRichTextBox.SelectionLength = 0;
myRichTextBox.Select(indx1stlinchr, 12);
myRichTextBox.SelectionColor = Color.Black;
myRichTextBox.Select((indx1stlinchr + 13), 19);
myRichTextBox.SelectionColor = Color.Blue;
if (network.Reserved_IP != null)
{
myRichTextBox.SelectionLength = 0;
myRichTextBox.Select((indx1stlinchr + 76), 13);
myRichTextBox.SelectionColor = Color.Green;
}
if (ipclassRange > 0)
{
myRichTextBox.Select(indx1stlinchr + 39, ipclassRange);
myRichTextBox.SelectionColor = Color.Green;
}
myRichTextBox.SelectionLength = 0;
}
if (line[i].StartsWith("Netmask") == true)
{
myRichTextBox.SelectionLength = 0;
myRichTextBox.Select(indx1stlinchr, 19);
myRichTextBox.SelectionColor = Color.Black;
myRichTextBox.Select((indx1stlinchr + 13), 19);
myRichTextBox.SelectionColor = Color.Blue;
myRichTextBox.Select((indx1stlinchr + 38), 38);
myRichTextBox.SelectionColor = Color.Red;
myRichTextBox.SelectionLength = 0;
if (super == false)
{
indxlinstrt = myRichTextBox.GetFirstCharIndexOfCurrentLine();
if (k == 1)
{
myRichTextBox.Select(indxlinstrt + indexlinedge, (def + 4) * -1);
subrange = CColor.FindeSubRange(Regex.Split(myRichTextBox.SelectedText, ""), network.Netmask_length, def);
k = 0;
}
myRichTextBox.Select(indxlinstrt + indexlinedge, subrange);
myRichTextBox.SelectionColor = Color.DarkViolet;
myRichTextBox.SelectionLength = 0;
}
}//.........etc
}
super = false;
k = 1;
}
Try this snippet:
private int GetFirstCharIndexOfLine(ITextDocument document, int line)
{
string value;
document.GetText(TextGetOptions.None, out value);
int size = 0;
while (value.Length > size)
{
ITextRange range = document.GetRange(size, size + 1);
size += range.Expand(TextRangeUnit.Line);
var lineIndex = range.GetIndex(TextRangeUnit.Line);
if (line == lineIndex)
{
//start of range is first line character index
return range.StartPosition;
}
size += 1;
}
return -1;
}
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);
}
}
}
}
I have a combobox outside my tabcontrol. In each tab control there is a datagridview full of values. In the combobox you can choose a conversion for all values. For example eV→meV.
When i am in the first tab and use the combobox there are no problems, but after i switch the tab and then wanna use the combobox the program list down however the whole combobox is full of try/catch
private void OpenB_Click(object sender, EventArgs e)
{
string[] result = new string[2];
bool lesen = false;
int Spalte = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Datagridview will be rested, so all values and rows are removed
for (int i = 1; i < Anzahl; i++)
{
DGV[i].Rows.Clear();
}
Anzahl = openFileDialog1.FileNames.Length;
counter = new int[Anzahl];
try
{
if (tabControl1.TabCount < Anzahl)
{
for (int i = 1; i <= Anzahl; i++)
{
if (i > tabControl1.TabCount)
{
string title = "Tab " + (tabControl1.TabCount + 1).ToString();
TabPage myTabPage = new TabPage(title);
tabControl1.TabPages.Add(myTabPage);
DataGridView NewDGV = new DataGridView();
NewDGV.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
NewDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NewDGV.Columns.Add("Energy", "Energy");
NewDGV.Columns[0].ReadOnly = true;
NewDGV.Columns.Add("Count Rate", "Count Rate");
NewDGV.Columns[1].ReadOnly = true;
NewDGV.Location = new System.Drawing.Point(3, 3);
NewDGV.Name = "NewDGV" + Convert.ToString(i);
NewDGV.RowHeadersVisible = false;
NewDGV.Size = new System.Drawing.Size(276, 379);
NewDGV.TabIndex = i;
foreach (DataGridViewColumn col in NewDGV.Columns)
col.SortMode = DataGridViewColumnSortMode.NotSortable;
NewDGV.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
DGV.Add(NewDGV);
tabControl1.TabPages[i - 1].Controls.Add(NewDGV);
}
}
}
else if (tabControl1.TabCount > Anzahl)
{
for (int i = tabControl1.TabCount - 1; i >= Anzahl; i--)
{
tabControl1.TabPages.Remove(tabControl1.TabPages[i]);
}
}
}
catch { }
try
{
//Double arrays and Datagridview will be attuned to the count of data
eV = new double[openFileDialog1.FileNames.Length][];
meV = new double[openFileDialog1.FileNames.Length][];
cm = new double[openFileDialog1.FileNames.Length][];
CR = new double[openFileDialog1.FileNames.Length][];
CRmax = new double[openFileDialog1.FileNames.Length][];
for (int i = 0; i < Anzahl; i++)
{
//Naming the columns after data names
string[] Dateiname = openFileDialog1.FileNames[i].Split('\\');
int L = Dateiname.Length;
tabControl1.TabPages[i].Text = Dateiname[L-1];
}
}
catch
{
}
//Datafiles will be read one by one
DataRead(result, ref lesen, ref Spalte);
}
}
/// Reading loop
///
/// double[] eV2 = Energy values of the current data file in eV
/// double[] meV2 = Energy values of the current data file in meV
/// double[] cm2 = Energy values of the current data file in cm^-1
/// double[] CR2 = Intensities of the current data file in CR
/// double[] CRmax2 = normalizied Intensities of the current data file in 1/CRmax
private void DataRead(string[] result, ref bool lesen, ref int Spalte)
{
for (Spalte = 0; Spalte < Anzahl; Spalte++)
{
string line;
lesen = false;
counter[Spalte] = 0;
try
{
Ursprung = openFileDialog1.FileNames[Spalte];
//initialize stream reader
System.IO.StreamReader file1 = new System.IO.StreamReader(openFileDialog1.FileNames[Spalte]);
//read line per line in stream reader
while (((line = file1.ReadLine()) != null))
{
counter[Spalte]++;
Count2 = counter[Spalte];
Count2 = Count2 / 2;
try
{
string[] splitter = line.Split(' ');
if ((splitter[0] == "S") && (splitter[1] == "0000"))
{
lesen = true;
counter[Spalte] = 0;
}
if (lesen == true)
{
//Rows will be filled an added with data value strings
if (counter[Spalte] % 2 == 0)
{
result[0] = splitter[2];
}
else
{
result[1] = splitter[2];
dataGridView1.Rows.Add();
DGV[Spalte].Rows.Add();
int Zeile = (counter[Spalte] - 1) / 2;
DGV[Spalte][0, Zeile].Value = result[0];
DGV[Spalte][1, Zeile].Value = result[1];
}
}
}
catch
{
continue;
}
}
//Streamreader is closed
file1.Close();
counter[Spalte] = counter[Spalte] / 2;
//Current datagridviw values are saved in arrays
//The conversions will be calculated and saved in new arrays
//So every unit gets its own array
double[] eV2 = new double[counter[Spalte]];
double[] meV2 = new double[counter[Spalte]];
double[] cm2 = new double[counter[Spalte]];
double[] CR2 = new double[counter[Spalte]];
double[] CRmax2 = new double[counter[Spalte]];
//Conversion calculation
for (int i = 0; i < counter[Spalte]; i++)
{
eV2[i] = Convert.ToDouble(DGV[Spalte][0, i].Value);
CR2[i] = Convert.ToDouble(DGV[Spalte][1, i].Value);
meV2[i] = 1000 * eV2[i];
cm2[i] = 8066 * eV2[i];
}
//Current file's arrays are saved in double arrays
eV[Spalte] = eV2;
CR[Spalte] = CR2;
meV[Spalte] = meV2;
cm[Spalte] = cm2;
for (int i = 0; i < counter[Spalte]; i++)
{
CRmax2[i] = CR2[i] / CR2.Max();
}
CRmax[Spalte] = CRmax2;
//Chosen conversion replaces values in datagridview
if (Hilfe == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV2[i];
}
}
else if (Hilfe == 2)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm2[i];
}
}
if (Hilfe2 == 1)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][1, i].Value = CRmax2[i];
}
}
}
catch
{
MessageBox.Show("Es ist ein Fehler beim Einlesen eingetreten");
}
}
}
/// Energy Unit
/// Choses between eV, meV, 1/cm
/// Datagridview values are replaced by the unit array values
/// Hilfe... Saves current energy unit
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int L = comboBox1.SelectedIndex;
try
{
if (L == 0)
{
Hilfe = 1;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
}
}
catch
{
}
}
if (L == 1)
{
Hilfe = 2;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = cm[Spalte][i];
}
}
}
catch
{
}
}
if (L == 2)
{
Hilfe = 0;
try
{
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = eV[Spalte][i];
}
}
}
catch
{
}
}
}
catch { }
}
Accept these answer if you dont know how to post your own answer?.
Answer:
Problem fixed. The reason was the dgv.autosizemode , when i deactivate it before the conversions it runs.
for (int Spalte = 0; Spalte < Anzahl; Spalte++)
{
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
for (int i = 0; i < counter[Spalte]; i++)
{
DGV[Spalte][0, i].Value = meV[Spalte][i];
}
DGV[Spalte].AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have designed a forms app which could have been better designed for unit testing by using business logic etc but at this stage I do not want to alter my code. It is an app which performs steganography whereby a message is embedded in an image using an LSB algorithm. I am currently trying to write a unit test for the button2 click event. When button2 is pressed; it will take text from two other textboxes and an image from a picturebox and run the LSB algorithm. Below is the test function. I create test values for the textboxes concerned. When I run the test I get: System.NullReferenceException: Object reference not set to an instance of an object. Does this refer to the object sender = null; EventArgs e = null;. Or is what I am doing even possible? Do I have to resort to NUnitForms? I have added button2_click after the test function:
public void button2_ClickTest()
{
StegApp_Accessor target = new StegApp_Accessor();
// TODO: Initialize to an appropriate value
object sender = null; // TODO: Initialize to an appropriate value
EventArgs e = null; // TODO: Initialize to an appropriate value
target.textBox4.Text = "123456";
target.textBox5.Text = "test message";
target.button2_Click(sender, e);
//Assert.Inconclusive("A method that does not return a value cannot
// be verified.");
//target.textBox4.Text = "123456";
//target.textBox5.Text = "test message";
/*
if (target.textBox4.Text.Length > 6 || target.textBox4.Text.Length < 0)
{
Assert.Fail("Key is out of range");
}*/
//Assert.IsInstanceOfType(target.b1,typeof(byte[]));
if(target.b1.Length != target.temp4.Length)
{
Assert.Fail("B1 array does not have the correct lenght");
}
Assert.IsInstanceOfType(target.image1,typeof(Bitmap));
Assert.IsInstanceOfType(target.sb,typeof(StringBuilder));
if(target.sb.Length != target.tmp3.Length)
{
Assert.Fail("Issue with Stringbuilder sb. Lenght not equal to 'tmp3'!");
}
Assert.Equals(target.z,target.StringLenght);
Assert.Equals(target.c, target.textBox5.Text.Length);
}
`private void button2_Click(object sender, EventArgs e)
{
//int x1, y1, z = 0;
try
{
// Convert String Into Byte Array
//byte[] sourceData = System.Text.ASCIIEncoding.ASCII.GetBytes(a);
// Convert Each Byte Into A Binary String
//foreach (byte thisByte in sourceData)
// binaryString.Append(Convert.ToString(thisByte, 2));
while (!key)
{
if (textBox4.Text == "")
{
//b1 = ASCIIEncoding.ASCII.GetBytes(textBox5.Text);
key = false;
MessageBox.Show("Error, enter your six digit key!");
return;
}
else if (textBox4.Text.Length > 6)
{
MessageBox.Show("Error, Key too long, try again!");
return;
}
else
{
//temp4 = textBox4.Text[0] + textBox4.Text[1] + textBox4.Text[2] + textBox4.Text[3] + textBox4.Text[4] + textBox4.Text[5] + textBox5.Text;
c = textBox5.Text.Length;
temp5 = c.ToString();
if (c <= 9)
{
temp5 = "000" + temp5;
}
else if (c <= 99)
{
temp5 = "00" + temp5;
}
else if (c <= 999)
{
temp5 = "0" + temp5;
}
else if (c <= 9999)
{
}
else
{
MessageBox.Show("Message too long for this tool,try again");
return;
}
temp4 = textBox4.Text + temp5 + textBox5.Text;
b1 = ASCIIEncoding.ASCII.GetBytes(temp4);
key = true;
}
}
//byte[] b1 = ASCIIEncoding.ASCII.GetBytes(textBox5.Text);
//b1 = Encoding.Unicode.GetBytes(a);
//Create the array to be returned.
tmp2 = new string[b1.Length];
//Interate through each byte
for (int i = 0; i < b1.Length; i++)
{
int x = b1[i];
tmp = "";
while (true)
{
if ((x % 2) == 1)
{
tmp = "1" + tmp;
}
else
{
tmp = "0" + tmp;
}
x /= 2;
if (x < 1) break;
}
//Make sure the value is 8 chars long.
tmp2[i] = tmp.PadLeft(8, '0');
}
//string a="";
for (int i = 0; i < b1.Length; i++)
{
//a = tmp2[i];
tmp3 = tmp3 + tmp2[i];
}
if (key)
{
tmp3 = "00" + tmp3;
}
else
{
tmp3 = "10" + tmp3;
}
sb.Append(tmp3);
//temp5 = c.ToString();
//z= c+1;
StringLenght = sb.Length;
byte Mask0 = 254;
byte Mask1 = 1;
byte NewRed = 0, NewGreen = 0, NewBlue = 0;
// Loop through the images pixels to reset color.
for (x1 = 0, y1 = 0; x1 < image1.Width && z < StringLenght; x1++)
{
for (y1 = 0; y1 < image1.Height && z < StringLenght; y1++)
{
Color pixelColor = image1.GetPixel(x1, y1);
//byte NewRed, NewGreen, NewBlue;
if (sb[z] == '0')
{
NewRed = Convert.ToByte(pixelColor.R & Mask0);
Color newColor = Color.FromArgb(NewRed, pixelColor.G, pixelColor.B);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
else
{
NewRed = Convert.ToByte(pixelColor.R | Mask1);
Color newColor = Color.FromArgb(NewRed, pixelColor.G, pixelColor.B);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
if (sb[z] == '0')
{
NewGreen = Convert.ToByte(pixelColor.G & Mask0);
Color newColor = Color.FromArgb(pixelColor.R, NewGreen, pixelColor.B);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
else
{
NewGreen = Convert.ToByte(pixelColor.G | Mask1);
Color newColor = Color.FromArgb(pixelColor.R, NewGreen, pixelColor.B);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
if (sb[z] == '0')
{
NewBlue = Convert.ToByte(pixelColor.B & Mask0);
Color newColor = Color.FromArgb(pixelColor.R, pixelColor.G, NewBlue);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
else
{
NewBlue = Convert.ToByte(pixelColor.B | Mask1);
Color newColor = Color.FromArgb(pixelColor.R, pixelColor.G, NewBlue);
image1.SetPixel(x1, y1, newColor);
pixelColor = image1.GetPixel(x1, y1);
z++;
if (z == StringLenght)
{
break;
}
}
//string binary1 = Convert.ToString(pixelColor.R, 2);
//char last1 = binary1[binary1.Length - 1];
}
}
MessageBox.Show("Message embedded");
//Color newColor = Color.FromArgb(NewRed, NewGreen, NewBlue);
//image1.SetPixel(x, y, newColor);
// Set the PictureBox to display the image.
//pictureBox1.Image = image1;
// Display the pixel format in Label1.
//label1.Text = "Pixel format: " + image1.PixelFormat.ToString();
}
catch (ArgumentException)
{
MessageBox.Show("There was an error." +
"Check the path to the image file.");
}
//pictureBox2.Image = image1;
//Byte[] buf = Encoding.Unicode.GetBytes(RetreivedMessage.ToString());
//Byte[] buf = Encoding.Unicode.GetBytes(RetreivedMessage.ToString());
//string result = System.Text.Encoding.Unicode.GetString(buf);
//String result = Encoding.Unicode.GetString(buf);
//StringBuilder r2 = new StringBuilder();
//foreach (Byte b in Encoding.Unicode.GetBytes(FinalRetreivedMessage))
//{
// r2.Append(Convert.ToString(b));
// }
//int v = 0;
//for (int i = 0; i < FinalRetreivedMessage.Length; i++)
// {
// v = v * 2 + (FinalRetreivedMessage[i] == '0' ? 0 : 1);
// }
//string result = v.ToString();
// copy the string as UTF-8 bytes.
// byte[] utf8Bytes = new byte[FinalRetreivedMessage.Length];
// for (int i = 0; i < FinalRetreivedMessage.Length; ++i)
// {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
// utf8Bytes[i] = (byte)FinalRetreivedMessage[i];
// }
//Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
// utf8Bytes = new byte[]{1,1,1,0,1,0,0,0};
// string result1 = Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
//string result1 = Encoding.UTF8.GetString(utf8Bytes);
// UTF8Encoding enc = new UTF8Encoding();
// string str = enc.GetString(utf8Bytes);
// Byte[] encodedBytes = enc.GetBytes(FinalRetreivedMessage);
// string message = encodedBytes.ToString();
// int count = FinalRetreivedMessage.Length / 8;
// var bollox = new byte[count];
// for (int i = 0; i < count; i++)
// bollox[i] = Convert.ToByte(FinalRetreivedMessage.Substring(i * 8, 8), 2);
// var bollox1 = new byte[count];
//for (int i = 0; i < count; i++)
//bollox1[i] = Encoding.Unicode.GetBytes(FinalRetreivedMessage.Substring(i * 8, 8));
// string result2 = bollox.ToString();
// string result3 = enc.GetString(bollox);
// string result4 = System.Convert.ToString(bollox);
// string StringIWant = BitConverter.ToString(bollox);
// string result5 = BitConverter.ToString(encodedBytes);
// string result6 = BitConverter.ToString(utf8Bytes);
// string result7 = BitConverter.ToString(Encoding.Unicode.GetBytes(FinalRetreivedMessage));
// string result8 = System.Convert.ToString(Encoding.Unicode.GetBytes(FinalRetreivedMessage));
// string result9 = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(FinalRetreivedMessage));
// string result10 = Encoding.Default.GetString(Encoding.Unicode.GetBytes(FinalRetreivedMessage));
}`
private void button2_Click(object sender, EventArgs e)
{
Embed();
}
public void Embed(string Embedkey, string EmbedMessage,Bitmap image3)
{
// embed message in image
}
public void EmbedTest()
{
StegApp target = new StegApp(); // TODO: Initialize to an appropriate value
string Embedkey = "123456"; // TODO: Initialize to an appropriate value
string EmbedMessage = "test2"; // TODO: Initialize to an appropriate value
Bitmap image3 = null; // TODO: Initialize to an appropriate value
image3 = new Bitmap(#"C:\Users\Admin\Documents\dt265\Project\Sky\sky-and-cloud.bmp",true);
string a="123456",b="test2";
target.Embed(Embedkey, EmbedMessage, image3);
//Assert.Inconclusive("A method that does not return a value cannot be verified.");
if (Embedkey.Length > 6 || Embedkey.Length < 0)
{
Assert.Fail("Key is out of range");
}
//Assert.IsInstanceOfType(target.b1,typeof(byte[]));
if(target.b1.Length != target.temp4.Length)
{
Assert.Fail("B1 array does not have the correct lenght");
}
Assert.IsInstanceOfType(target.image1,typeof(Bitmap));
Assert.IsInstanceOfType(target.sb,typeof(StringBuilder));
if(target.sb.Length != target.tmp3.Length)
{
Assert.Fail("Issue with Stringbuilder sb. Lenght not equal to 'tmp3'!");
}
if(target.z != target.StringLenght)
{
Assert.Fail("z != StringLenght");
}
if (target.c != EmbedMessage.Length)
{
Assert.Fail("c is not the lenght of the Message!");
}
}
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.