I have a function that is giving me a Console.Writeline output, but it's not writing the information to my richTextBox.
public static void FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
{
//Create a list to hold all the fonts
var listOfDisplayFonts = new List<string>();
string[] arrayOfDisplayFonts = listOfDisplayFonts.ToArray();
//Display font name for each font that exists in the dragdrop rich text box.
if (dragDropSourceData.Contains(actualFontName[0]) || dragDropSourceData.Contains(actualFontName[1]) || dragDropSourceData.Contains(actualFontName[2]))
{
//If the font doesn't already exist in the output textbox.
if (!outputData.Contains(displayFontName))
{
//Add font to the output textbox.
listOfDisplayFonts.Add(displayFontName);
foreach (string s in listOfDisplayFonts)
{
//Add strings from list to text box.
outputData += string.Join(Environment.NewLine, s) + "\n";
}
//Clear fonts from the list (They've already been added to the textboxes).
listOfDisplayFonts.Clear();
}
}
Console.WriteLine(outputData);
}
In this example, outputData is equal to richTextBox1.Text (the last parameter). When I am using this function in my Main.cs, these are the parameters.
FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt, EscapeSequence.fontDispName, dragDropRichTextBox1.Text, richTextBox1.Text);
Why is it that the Console.Writeline is giving me the proper output, but richTextBox1.Text remains empty? I know the function is proper, because if I call it directly from my Main.cs (and fill the actual parameter values into the function), it works fine. This is mostly an educational exercise to help me learn.
You're passing the text string of richTextBox1 to the method. The statement outputData += string.Join(Environment.NewLine, s) + "\n"; would concatenate text and create a new string (a string is immutable) but the original text string that was passed remains the same.
You need to assign back the result to richTextBox1:
richTextBox1.Text = FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt,
EscapeSequence.fontDispName, dragDropRichTextBox1.Text, richTextBox1.Text);
Of course in this case you should change the method's return type from void to string and return outputData; at the end.
In this example, outputData is equal to richTextBox1.Text (the last parameter).
It might have the same string value when you start, but it is not the same variable.
You pass in outputData.
FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
Then you modify it a bunch, and finally write it to the console.
Console.WriteLine(outputData);
You never assign your new outputData back to any control.
The outputData that you passed in is a different one than the final one you write to the console, because strings are immutable. That's a fancy way of saying you don't modify the original string, but rather you create a new one.
To solve the problem, assign outputData to the control. You can do that within the function you posted if it has access to the control, or it can return outputData back instead of having a void return type.
Quick fix:
At the end of your function, do this (obviously changing the return type to string from void as well):
return outputData;
So your function becomes:
public static string FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, string outputData)
{
// everything the same as before...
return outputData;
}
Then you can call it like this:
richTextBox1.Text = FontFinder.FindFeatureSecurityEsc(EscapeSequence.fontEsc12pt,
EscapeSequence.fontDispName, dragDropRichTextBox1.Text,
richTextBox1.Text);
Strings are immutable. That means whenever you concatenate or do any other kind of string manipulation you are actually creating a new string. Your control's .Text property is still pointing to the old string so it won't "see" any of the changes.
The other approach here would be to change your function to take the control instead of the just the string:
public static void FindFeatureSecurityEsc(string[] actualFontName, string displayFontName, string dragDropSourceData, RichTextBox outputDataCtrl)
{
var outputData = outputDataCtrl.Text;
// rest of your function as before
outputDataCtrl.Text = outputData;
}
Which approach is better is up to you.
Looks like you are only using the richTextBox1.Text to display the output, since you are passing it by value. Hence the Console.Writeline output is correct. You would be able to get the result in the richTextBox.Text if you pass it by ref. That way you don't even have to change the return type of your method and assign it back to the control's text.
Related
I need to replace multiple strings in a textfile. This is my code:
List<string> list = new List<string>();
string Text = File.ReadAllText(temp);
list.Add(Text.Replace("name", name));
list.Add(Text.Replace("name2", name2));
list.Add(Text.Replace("1.0000", CR));
list.Add(Text.Replace("0.6590", CG));
list.Add(Text.Replace("0.0000", CB));
foreach (string txt in list)
{
File.WriteAllText(path, txt);
}
When I debug I can see the strings beeing replaced one after one, but when the next string is about to be replaced, the last string will then go back to its old value. Is there a way to replace multiple strings in a textfile?
You don't need a list for this, but you do need to save the changes in the resulting string each time you do a replacement, otherwise you lose the changes.
The Replace method returns a new string with the replacement, so you can chain the calls to Replace and it will end up returning a string with all your changes.
Here's an example:
string text = File.ReadAllText(temp)
.Replace("name", name)
.Replace("name2", name2)
.Replace("1.0000", CR)
.Replace("0.6590", CG)
.Replace("0.0000", CB);
File.WriteAllText(path, txt);
I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.
Problem I currently have:
My server returns data back to the client, this includes a name. Now I want the client to grab this name and compare it. However for the past 3 hours I am stuck at this problem and I dont want to cheap fix around it.
My server returns a value and then a name, ex: random23454#NAMEHERE
I split the value using:
string[] values = returndata.Split('#');
And then I am doing:
if (textBox3.Text == values[1]) {
MessageBox.Show("equal");
}
However, the problem here is. I cant get it to be equal, I tried other methods but it just dont display equal.
What I have done:
Print textBox3.Text to a textbox and print values[1] to a other textbox and compared with my eye and mouse (Using invoke due to threading).
Used the .Trim() function
Using the .ToString() on values[1] (Just for the hell of it)
Assigned them both to a complete new string, trimmed them and compared them
Dragged the comparing outside the thread using:
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
and perform the same check.
My code:
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
if (readData.Contains("#") && readData.Contains("random"))
{
string[] values = returndata.Split('#');
string name = values[1].Trim();
if (textBox3.Text == name)
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
this.Invoke((MethodInvoker)delegate()
{
outside(name);
});
}
What else can I do? I just dont understand that it is not equal..
Thanks in advance.
The data you're getting back from the server could be an array of bytes. Try converting the response to a string first before splitting. Also try printing the response (or the response's type) to console to see what you get before going any further.
Also make sure the length of each string is the same. Maybe give utf-8 a try instead of ASCII? Like so:
System.Text.Encoding.UTF8.GetString(inStream);
string name = values[1].Trim();
I think you want values[2] here. The way I read the documentation for Split, the element at index 1 will be the (blank) separator indicator.
I have written a simple program in C# in which
messages are displayed using a statement like:
{
MessageBox.Show("Enter the Correct Values. ", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
Some text box contents are written to text files using StreamWriter.
In both case, in addition to the correct content, I also get the prefix:
System.Windows.Forms.TextBox, Text:
I get a similar prefix (and a suffix of \r\n) when using StreamReader to read the contents of a text file.
How do I avoid this?
Without seeing your code, I'm guessing you're passing the TextBox directly to the StreamWriter, rather than passing the TextBox.Text property value. Passing the TextBox reference directly to StreamWriter.WriteLine will call TextBox.ToString() to get a string value that it can write, and it looks like TextBox.ToString() is generating that prefix. Pass in TextBox.Text, and you shouldn't see it anymore.
The best and easiest soloution to this i have ever found is to split the string and use the required string
string str = TextBox1.Text;
char[] spearator = { ' ' };
String[] splitStr = str.Split(spearator);
string RequiredString = splitStr[1];
Try this code hope this will work
txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
i want to find the last index of "," in my text and then remove that , but it is not working. Any Idea? txtBeautified is a richtextbox.
Are you retrieving the result of the operation?
value = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
If you are changing the value of the text box, you need to assign the result back to the text box:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
Explanation: Strings cannot be changed. Functions that operate on strings do not change the strings, but return new strings. Therefore, the Remove function returns a string representing the result. To make use of this string, you will need to assign it to a variable/property or pass it into another function call.
Remove is a function. call should be:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1)
Keep in mind that a string is immutable, so the Remove function returns you a new string. You'd need to reassign that new string back to the text box, like:
txtBeautified.Text = txtBeautified.Text.Remove(txtBeautified.Text.LastIndexOf(","), 1);