Weird spacing in Hex to String - c#

I am trying to make a hex to string converter and for some reason the spacing between bytes in the conversion is multiplied by 2.
I would like it to spit out a single space between characters,
private void button2_Click(object sender, EventArgs e)
{
try
{
textBox1.Clear();
textBox2.Text = textBox2.Text.Replace(" ", "");
string StrValue = "";
while (textBox2.Text.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
textBox1.Text = textBox1.Text + StrValue + " ";
}
}
catch (Exception ex)
{
MessageBox.Show("Conversion Error Occurred : " + ex.Message, "Conversion Error");
}
}
so "41 41" converted would look like "A A", but this is what happens:
image
Does anybody see what I am doing wrong?

In this line
textBox1.Text = textBox1.Text + StrValue + " ";
you consequently append the result of calculations to your TextBox1.
So, after the first iteration the result is A, you append it and a whitespace to TextBox1.
Then, you take the second 41 and convert it. Now, StrValue is AA and you append it and space to TextBox1, and so on.
You need to move this line out of your while loop:
textBox1.Clear();
textBox2.Text = textBox2.Text.Replace(" ", "");
string StrValue = "";
while (textBox2.Text.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
}
textBox1.Text = StrValue;
As some people mentioned in comments, you need to stop working with TextBoxes this way. It is pretty confusing. You may want to do the following:
private string HexToString(string hex)
{
string result = "";
while (hex.Length > 0)
{
result += Convert.ToChar(Convert.ToUInt32(hex.Substring(0, 2), 16));
hex = hex.Substring(2); // no need to specify the end
}
return result;
}
Then, in your button click event or wherever else:
textBox1.Text = HexToString(textBox2.Text.Replace(" ", ""));
As simple as that. Or you can even move replacing the whitespaces in the method. Now, this code is readable and is logically separated.

The problem seems to be caused by the accumulated value in StrValue. You should define that variable inside your while, and assign it only (don't append a new value).
while (textBox2.Text.Length > 0)
{
string StrValue = System.Convert.ToChar(System.Convert.ToUInt32(textBox2.Text.Substring(0, 2), 16)).ToString();
textBox2.Text = textBox2.Text.Substring(2, textBox2.Text.Length - 2);
textBox1.Text = textBox1.Text + StrValue + " ";
}

Related

c# Simple division having issues with messagebox not displaying

Trying to use a button to divide text inputs. I already have the add/sub/mult done and they work fine just the division does not. Below is my code any help is appreciated. The code seems ok my issue is that the messagebox isn't displaying
private void myDivideButton_Click(object sender, RoutedEventArgs e)
{
int ans = 0;
try
{
ans = int.Parse(myInput1.Text) / int.Parse(myInput2.Text);
MessageBox.Show("The values being divided are " + myInput1.Text + "/" + myInput2.Text + "=" + ans);
}
catch (Exception ex)
{
myInput1.Text = "0";
myInput2.Text = "0";
}
}
}
}
The division of 2 integers is an integer. If you want a double-precision floating point number, you have to cast either of the input to a double or decimal. So, if you want a result with decimals, try this:
double ans = 0;
try
{
ans = double.Parse(myInput1.Text) / double.Parse(myInput2.Text);
MessageBox.Show("The values being divided are " + myInput1.Text + "/" + myInput2.Text + "=" + ans);
}
catch (Exception ex)
{
myInput1.Text = "0";
myInput2.Text = "0";
}

C# Writing to a csv file where a value has a string literal inside of it

I am writing to a csv file and one of the values to be written to a row has a string literal in it as part of the value and I need it to remain in the value:
Example of the value:
"<span><span style=\"font-family: arial,sans-serif;\"><\span><\span>"
What is happening is the instead of keeping this under one column the comma forces it into the next column as the writer thinks this is what it is supposed to do.
My method:
var value = "";
var fileReadIn = new StreamReader(fileName);
var headerFields = CsvRowToStringArray(fileReadIn.ReadLine());
fileReadIn.Close();
for (int i = 0; i < headerFields.Length - 1; i++)
{
if (dict.ContainsKey(headerFields[i]))
{
if (dict[headerFields[i]].Contains("\n"))
{
Console.WriteLine("hell");
Console.ReadKey();
value += "\"" + dict[headerFields[i]].Replace("\n", #"\n").Replace(#"\", #"""\""" ).Replace(#"/", #"""/""")
+"\"" + ",";
}
else
{
value += #"""" + dict[headerFields[i]] + #"""" + ",";
}
}
else
{
value += #"""" + "Null" + #"""" + ",";
}
}
dict.Clear();
return value;
As long as the string literal is not present it wraps the rows quotes and that fixes any comma issue, however I've tried using both methods below however am not having any luck

Project almost complete, output is wrong and will not display properly, have been unable to find my error.

I am almost finished with the program, but my output is wrong, and after 5 hours, I am still unable to figure out what I did wrong, and thought it may be helpful to seek a fresh set of eyes. I have a Demo program given by my instructor, so I took a screen shot to show clearly what it should look like.
My code for that chunk is this:
//array add student data to the array
if (currentStudentArrayIndex >= constArrayMaxSize)
{
MessageBox.Show("Array is full, cannot add any more to the array");
}
else
{
arrayNames [currentStudentArrayIndex] = studentName;
arrayGrades [currentStudentArrayIndex] = studentGrade;
MessageBox.Show("Student data has been entered into array index " + currentStudentArrayIndex);
textBoxName.Text = "";
textBoxGrade.Text = "";
}
//array output
currentStudentArrayIndex = currentStudentArrayIndex + 1;
}
//array display
private void buttonDisp_Click(object sender, EventArgs e)
{
string myString = "";
string studentName = "";
int studentGrade = 0;
myString = "Student Data Entered So Far:\n";
//loop through array
for(int i = 0; i < arrayNames.Length; i++)
{
myString = myString +
"Array[" + i + "] ==> " +
"Student #" + (i + 1);
if (arrayGrades[i] == 0)
{
myString = myString + " (NOT ENTERED)";
}
else
{
myString = myString +
" Name:" +arrayNames[i] +
" Grade:" + arrayGrades[i].ToString("c");
studentName = studentName + arrayNames[i];
studentGrade = studentGrade + arrayGrades[i];
}
//output
labelDisplay.Text = myString;
}
Obviously myString isn't working, but I'm unsure why, what did I do to it? Any suggestions, useful links, or guidance is much appreciated!
Button buttonDisp was incorrect. Using the correct button name corrected the problem, allowing the information to display properly.

Reversed for loop

I made this small nested for loop, and it shows no error in C# whatsoever,
but when I try to run my small program I get the following error in my TextBox:
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox,
Text: Syst...
Here is my code:
int number = textBox.Text..ToString();
for (int row = 0; row < number; row++)
{
for (int x = number - row; x > 0; x--)
{
textBox2.Text = textBox2.Text + "X";
}
textBox2.Text = textBox2 + Environment.NewLine;
}
My result should be something like this:
XXXX
XXX
XX
X
I can't figure out what may cause this error.
You can't assign a string to a number. You need to convert it:
// int number = textBox.Text..ToString();
int number;
if (!int.TryParse(textBox.Text, out number)
{
// Handle improper input...
}
// Use number now
In addition, when you add the newline, you need to actually append to the Text property, not the TextBox itself:
textBox2.Text = textBox2.Text + Environment.NewLine;
Instead of
textBox2.Text = textBox2 +
use
textBox2.Text = textBox2.Text +
in the last line.
That's it ;-)
textBox2.Text = textBox2 + Environment.NewLine;
Should be
textBox2.Text = textBox2.Text + Environment.NewLine;
System.Windows.Forms.TextBox is just class name
You're missing a .Text in the second to last line. It should be:
textBox2.Text = textBox2.Text + Environment.NewLine;
^^^^^
or just:
textBox2.Text += Environment.NewLine;
int number = textBox.Text..ToString();
Suppose that was a typo? Either way, check if the value is numeric first.
if (int.TryParse(textBox.Text, out number))
{
//run your loop here
}
Also,
textBox2.Text = textBox2 + Environment.NewLine;
should be:
textBox2.Text = textBox2.Text + Environment.NewLine;
You cannot assign string to an int , what you are doing as:
int number = textBox.Text..ToString();
Better option is to use int.TryParse(textBox.Text, out number)
AND
Change
textBox2.Text = textBox2 + Environment.NewLine;
to
textBox2.Text = textBox2.text + Environment.NewLine;
Edit:
Even if you change 2 dots to 1, it will give error for int number = textBox.Text.ToString(); - you can't assign string to int
You have two dots here.
textBox.Text..ToString();
This should throw a compilation error by the way. And you can't assign it to a variable of type integer.
textBox2.Text = textBox2 + Environment.NewLine;
You have to call a method of the textbox here, presumably textBox2.Text.
This might inspire you to think about this problem differently:
// I created a simple textbox class so I could do this in a console app
var textBox = new TextBox();
var textBox2 = new TextBox();
textBox.Text = "4";
var number = Convert.ToInt32(textBox.Text);
var descendingXStrings = Enumerable.Range(1, number)
.Select(n => new string('X', n))
.Reverse();
textBox2.Text = string.Join(Environment.NewLine, descendingXStrings);
Console.WriteLine(textBox2.Text);
CW as this does not answer the question directly.
Try this
int number = int.Parse(textBox1.Text);
for (int row = 0; row < number; row++)
{
for (int x = number - row; x > 0; x--)
{
textBox2.Text = textBox2.Text + "X";
}
textBox2.Text = textBox2.Text + Environment.NewLine;
}
Convert TextBox Value in integer
Change textBox2 to textBox2.Text in second last line
Use textBox as multiline textbox

How Can I Prevent RichTextBox Append which Can Cause OutOfMemory?

My Objective is keep logs line by line with RichtextBox control, But I am worry that when the lines reach to certain point , my window form will be hung or run of out memory..
Can any one show me how can i prevent this will happen, I have in mind maybe limit 300 lines with FIFO , or 500 lines then empty and refresh again..However i am not sure How Can i implement this.
void WriteLog(string txt)
{
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
If you want to delete lines than try to use this
void WriteLog(string txt)
{
if(richTextBox1.Lines.Count() == 100)
{
DeleteLine(0);
}
richTextBox1.AppendText(txt + Environment.NewLine);
richTextBox1.HideSelection = false;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
}
private void DeleteLine(int a_line)
{
int start_index = richTextBox1.GetFirstCharIndexFromLine(a_line);
int count = richTextBox1.Lines[a_line].Length;
// Eat new line chars
if (a_line < richTextBox1.Lines.Length - 1)
{
count += richTextBox1.GetFirstCharIndexFromLine(a_line + 1) -
((start_index + count - 1) + 1);
}
richTextBox1.Text = richTextBox1.Text.Remove(start_index, count);
}
try this code to remove last line and then append text then you'll have just 300lines limit:
private void RemoveLastLineAfter300()
{
if(richTextBox1.TextLength != 0)
{
int totalCharacters = richTextBox1.Text.Trim().Length;
int totalLines = richTextBox1.Lines.Length;
string lastLine = richTextBox1.Lines[totalLines - 1] + "\n";
string copyOfLastLine = richTextBox1.Lines[totalLines - 1];
if(totalLines > 300)
{
string newstring = richTextBox1.Text.Substring(0, totalCharacters - lastLine.Length);
richTextBox1.Text = newstring;
}
}
}
And if you want to clear text(if I undertood correctly) after 500lines just check on TextChanged event
if(richTextBox1.Lines.Length > 500)
richTextBox1.Text = string.Empty;
I hope this helps you.

Categories