Converting a program from console to windows form C# - c#

I am trying to convert a program from console to windows form but the problem is that the output is not showing on my textbox. My program is that user inputs how many number of rows.
int n = int.Parse(textbox1.Text);
int counter1 = 1,counter2 = 1,size = n + n -1;
for(int i = 0;i<size;i++){
for(int j = 0;j<size;j++){
if(i<n-1){
if(j<n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1++;}
else{
textBox2.Text = " ";
} }
else{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2++;}
else{
textBox2.Text = " ";
}
} }
else if(i == n- 1 && j == n-1){
textBox2.Text = "{0} " + counter1;
counter1--;
counter2--; }
else if(i == n-1 && j != n-1){
textBox2.Text = " ";
}
else if(i > n-1){
if(j>n-1){
if(i == j){
textBox2.Text = "{0} " + counter1;
counter1--;
}
else{
textBox2.Text = " ";
} }
else
{
if(i + j == size-1){
textBox2.Text = "{0} " + counter2;
counter2--;
}
else{
textBox2.Text = " ";
}
} } }
textBox2.Text = " ";
}
The program is to display the input x number pattern. Thanks in advance.

You are resetting the text of textBox2 every time. You should use the += operator instead of =.
Side note: You should also use the special '\n' character when you need a new line.

Related

c# how to color each lines in richtextbox

I need to color each line depends on the last char in each string form list. This is my code and it's always make the last line green. What's wrong with it?
List<string> plik = File.ReadAllLines(path).ToList();
string pom;
int size = plik.Count;
richTextBox1.Clear();
for (int i = 0; i < size; i++)
{
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
pom =plik[i];
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
// richTextBox1.Select(0, pom.Length);
if (pom.Substring(pom.Length - 1) == "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) == "n" ? Color.Red :Color.Red;
}
if(pom.Substring(pom.Length - 1) != "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) != "n"?Color.Green:Color.Green;
}
}
just replace
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
by
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
Append the text instead of modifying it in whole. Using += will replace the entire string and hence you'll lose the set color each time. Use AppendText instead.
Also you can remove the unnecessary ifs in your code. This should work:
for (int i = 0; i < size; i++)
{
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
richTextBox1.SelectionBackColor = plik[i][plik[i].Length - 1] == 'n' ? Color.Red : Color.Green;
}

PigLatin Translator Crashing C#

For some reason when I run this code I am noticing that the letter "I or i" or word "it" crashes the program. Also when I just click translate with nothing entered it crashes as well. I have gone over this code over and over but I can't find the problem. Any suggestions?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnTranslate_Click(object sender, EventArgs e)
{
String input = Convert.ToString(txtInput.Text.Trim());
String inputTr = Regex.Replace(input, " {2,}", " ");
String pigLatin = "";
String temp = "";
String restOfWord = "";
String vowels = "AEIOUaeiou";
String consonants = "YBCDFGHJKLMNPQRSTVXWZbcdfghjklmnpqrstvxwzy";
string[] words = inputTr.Split();
foreach (string word in words)
{
if (string.IsNullOrEmpty(txtInput.Text))
{
MessageBox.Show("Text must be entered");
}
int index = word.IndexOfAny(new char[] { 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' });
if (Regex.IsMatch(word, "[##$%0-9]"))
{
pigLatin += word + " ";
}
else if (!(char.IsPunctuation(word.Last())) && vowels.Contains(word[0]) && word.Contains(word.Substring(1, 2).ToLower()))
{
pigLatin += word + "way" + " ";
}
else if (char.IsPunctuation(word.Last()) && vowels.Contains(word[0]) && word.Contains(word.Substring(1, 2).ToLower()))
{
pigLatin += word.Substring(0, word.Length - 1) + "way" + word.Last() + " ";
}
else if (!(char.IsPunctuation(word.Last())) && consonants.Contains(word[0]) && word.StartsWith(word.Substring(0, 1).ToLower()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
pigLatin += restOfWord + firstPart + "ay" + " ";
}
else if (char.IsPunctuation(word.Last()) && consonants.Contains(word[0]) && word.StartsWith(word.Substring(0, 1).ToLower()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
pigLatin += restOfWord.Substring(0, restOfWord.Length - 1) + firstPart + "ay" + restOfWord.Last() + " ";
}
else if (!(char.IsPunctuation(word.Last())) && word.Contains(word.ToUpper()) && vowels.Contains(word.Substring(0, 1).ToUpper()))
{
pigLatin += word + "WAY" + " ";
}
else if (char.IsPunctuation(word.Last()) && word.Contains(word.ToUpper()) && vowels.Contains(word.Substring(0, 1).ToUpper()))
{
pigLatin += word.Substring(0, word.Length - 1) + "WAY" + word.Last() + " ";
}
else if (!(char.IsPunctuation(word.Last())) && word.StartsWith(word.Substring(0, 1).ToUpper()) && consonants.Contains(word.Substring(0, 1).ToUpper()) && word.Contains(word.Substring(1, 2).ToLower()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
pigLatin += restOfWord.Substring(0, 1).ToUpper() + restOfWord.Substring(1, restOfWord.Length - 1).ToLower() + firstPart.ToLower() + "ay" + " ";
}
else if (char.IsPunctuation(word.Last()) && word.StartsWith(word.Substring(0, 1).ToUpper()) && consonants.Contains(word.Substring(0, 1).ToUpper()) && word.Contains(word.Substring(1, 2).ToLower()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
temp = restOfWord.Substring(0, 1).ToUpper() + restOfWord.Substring(0, restOfWord.Length - 1).ToLower() + firstPart.ToLower() + "ay" + restOfWord.Last() + " ";
temp = temp.Remove(0, 1);
pigLatin += temp.Substring(0, 1).ToUpper() + temp.Substring(1, temp.Length - 1).ToLower() + " ";
}
else if (!(char.IsPunctuation(word.Last())) && word.Contains(word.ToUpper()) && consonants.Contains(word.Substring(0, 1).ToUpper()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
pigLatin += restOfWord.ToUpper() + firstPart.ToUpper() + "AY" + " ";
}
else if (char.IsPunctuation(word.Last()) && word.Contains(word.ToUpper()) && consonants.Contains(word.Substring(0, 1).ToUpper()))
{
string firstPart = word.Substring(0, index);
restOfWord = word.Substring(index, word.Length - index);
pigLatin += restOfWord.Substring(0, restOfWord.Length - 1).ToUpper() + firstPart.ToUpper() + "AY" + word.Last() + " ";
}
txtOutput.Text = pigLatin;
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInput.Text = "";
txtOutput.Text = "";
txtInput.Focus();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
}
}
In several places throughout your code you have "Substring(1, 2)" - if the word you are currently processing is short than three characters long then you will get an exception because you are trying to get a substring that extends beyond the end of the string.
You need to add length checking into your code.
e.g.
...
...
else if (!(char.IsPunctuation(word.Last())) && vowels.Contains(word[0]) &&
&& (word.Length >= 3) && word.Contains(word.Substring(1, 2).ToLower()))
...
...
Just as a note on debugging - you could put a (conditional) breakpoint on the line where the exception occurs & then check each individual part of your if statement in the Immediate Window (copy & paste) to see which clause is causing the exception.

Testing all cells in datagridview

for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}
Shouldn't that be? Since you yourself adding rows to your gridview by calling Add() method as can be seen in your posted code
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(),
No idea since I don't know your requirement but to me it feels like you wanted to have the other part as else block.
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}

Check next loop iteration data unless at end of loop c#

I'm making a program which is creating an ASCII image. Based on the asterix input it produces different things. To start I'm making a basic outline however I have an issue where I cannot add something when checking last for loop iteration.
Method code:
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if(li < curLine.Length - 1)
{
if (curLine[i] == '*' && curLine[i + 1] != '*')
{
outputLine1 += "+";
outputLine2 += "|";
}
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}
When I run this, it works fine however will not add '+' and '|' to the last line of outputLines. This is because the line :
if(li < curLine.Length -1)
However without the -1 it will throw an exception because I am using [i+1] to decide something. Is there a way to check only if it won't throw an exception?
you can check if the end of the array has been reached by using the OR ( || ) statement. If the first statement of the OR statement returns true, the second is not checked. This is called short-circuiting. No error should be thrown in this case.
private List<string> DrawOutline(List<string> inputLines)
{
List<string> output = new List<string>();
int door = r.Next(0, inputLines.Last().Length);
for (int li = 0; li < inputLines.Count; li++)
{
char[] curLine = inputLines[li].ToCharArray();
string outputLine1 = string.Empty;
string outputLine2 = string.Empty;
for (int i = 0; i < curLine.Length -1; i++)
{
Console.WriteLine(curLine[i]);
if (curLine[i] == '*')
{
outputLine1 += "+---";
outputLine2 += "| ";
}
else
{
outputLine1 += " ";
outputLine2 += " ";
}
if (curLine[i] == '*' && (curLine.Length == i+1 || curLine[i + 1] != '*'))
{
outputLine1 += "+";
outputLine2 += "|";
}
}
output.Add(outputLine1);
output.Add(outputLine2);
}
return output;
}
Change if (li < curLine.Length - 1) to if (i < curLine.Length - 1)

How do I can optimize inserting/replacement element in to the List<string>

I have some code:
var result = new List<string>;
...
for (var i = 0; i < level; ++i)
if (result.ElementAtOrDefault(i) == null)
result.Insert(i, " " + positions[i]);
else
result[i] += " " + positions[i];
if (result.ElementAtOrDefault(level) == null)
result.Insert(level, " " + currentPosition);
else
result[level] += " " + currentPosition;
Can I do this without checking element for null from i-position? I need to add a part of string in i-position. But I have "ArgumentOutOfRangeException" if element wasn't created. Also method "insert" don't replace the element but push back it.
I tried to get data from "ArgumentOutOfRangeException" (which index called this exception) but I've failed.
You can reduce using ElementAtOrDefault with adding some condition like this
int i;
for (i = 0; i < level && i < result.Count; ++i){
//change existing items
result[i] += " " + positions[i];
}
for (int j = 0, countAdd = level - result.Count; j < countAdd; ++j)
//add new items
result.Add(" " + positions[i+j]);
//add current
if (level >= result.Count)
result.Add(" " + currentPosition);
else
result[level] += " " + currentPosition;

Categories

Resources