Set specific line of multiline TextBox in c# - c#

Hello I am new to C Sharp & Windows Forms. I am unable to set the specific string of a multiline TextBox. I have tried below things so far.
textBox1.Lines[1] = "welcome to stackOverflow";
The above code does not give a compile time error but when I saw the result using Debug mode it was not expected.
Then i was also reading this MSDN article but in this there is a new collection created by using stream[] constructor but still the same problem arises.

It should give compiler error because you are trying to assign a string to char here:
textBox1.Text[1] = "welcome to stackOverflow";
Text property is of type string, when you use indexer on a string it gives you the char at that position. And also string is immutable so you can't really change a character at specific position without creating a new string.
You should set the Text directly like this:
textBox1.Text = "welcome to stackOverflow";
Or if you have more than one line in an array of string you should set the Lines property:
var lines = new [] { "foo", "bar" };
textBox1.Lines = lines;

Any value that you set directly to textBox1.Lines will be effected to textBox1.
There is a solution to resolve your problem. I think it's best way.
You have to clone the current value of your textbox. Then you set new value on it. Finally, you set back to textbox.
var curValue = (string[])textBox1.Lines.Clone();
curValue[1] = "welcome to stackOverflow";
//Set back to textBox1
textBox1.Lines = curValue;

Related

Checking a checkbox based on a textbox value

The code I have here is supposed to load three separate values from three lines in a .txt file. This works fine so far. LOAD1 works well, and gets converted to an integer and then put back into the program as expected.The trouble is LOAD2.
What I'm trying to do: I want this bit of code to check whether the text "counter clockwise" is the text in LOAD2. If it is, I want it to automatically check a checkbox (RotDir, which is also available for manual input in the main program). The only other available text that can be in that textbox is "Clockwise", which should leave RotDir unchecked. So ticking a checkbox by using input from a textbox, is this possible?
I figured, this can be solved with a basic true/false kind of statement, since it is only two values. However, this does not seem to work. Does anyone have an idea how I could solve this?
StreamReader sr = new StreamReader("C:\\Users\\Gebruik\\Desktop\\Settings.txt");
string[] lines = sr.ReadToEnd().Split(new char[] { '\n' });
LOAD1.Text = lines[3];
LOAD2.Text = lines[7];
LOAD3.Text = lines[10];
int A = Int32.Parse(LOAD1.Text);
ServoSpd.Value = A;
label1.Text = LOAD1.Text;
if (LOAD2.Text == "Counter Clockwise")
{
ServoDir.Checked = true;
}
else
{
ServoDir.Checked = false;
}
ServoDir.Checked = LOAD2.Text.ToLower() == "counter clockwise"
This will set the Checked property of your CheckBox to true if lowercase trimmed Load2.Text is "counter clockwise", otherwise it will be false.
If you are using strings to set some values try to do lowercase/uppercase comparison and also trim the string so that whitespaces are removed from the start and end of string.
EDIT:
Forgot to mention that you should try replace the whole if statement with the above code.
EDIT:
If above code does not work, try to set the IsChecked property to true/false.

Change Particular line of Multiline textbox in C#

I am unable to Change the specific string of a multiline TextBox.
suppose first line of multiline textbox is "Hello" & second line is "Bye".But when i trying to change the value of second line like below.
textBox1.Lines[1] = "Good bye";
When I saw the result using Debug mode it was not "Good bye".
I also read this MSDN article & this stackoverflow question but can't get the desired answer.
As MSDN states (the link you provided):
By default, the collection of lines is a read-only copy of the lines in the TextBox.
To get a writable collection of lines, use code
similar to the following: textBox1.Lines = new string[] { "abcd" };
So, you have to "take" Lines collection, change it, and then return to TextBox. That can be achieved like this:
var lines = TextBox1.Lines;
lines[1] = "GoodBye";
TextBox1.Lines = lines;
Alternatively, you can replace text, like Wolle suggested
First you need assign textBox1.Lines array in variable
string[] lines = textBox1.Lines;
Change Array Value
lines[1] = "Good bye";
Reassign array to text box
textBox1.Lines=lines;
According to MSDN
By default, the collection of lines is a read-only copy of the lines
in the TextBox. To get a writable collection of lines need to assign
new string array
Working with TextBox lines via Lines property are extremely ineffective. Working with lines via Text property is a little better, but ineffective too.
Here the snippet, that allows you to replace one line inside TextBox without rewriting entire content:
public static bool ReplaceLine(TextBox box, int lineNumber, string text)
{
int first = box.GetFirstCharIndexFromLine(lineNumber);
if (first < 0)
return false;
int last = box.GetFirstCharIndexFromLine(lineNumber + 1);
box.Select(first,
last < 0 ? int.MaxValue : last - first - Environment.NewLine.Length);
box.SelectedText = text;
return true;
}
You could try to replace the text of second line like this:
var lines = textBox.Text.Split(new[] { '\r', '\n' }).Where(x => x.Length > 0);
textBox.Text = textBox.Text.Replace(lines.ElementAt(1), "Good bye");

Bold Specific Elements from JSON Array in Rich Textbox

I'm currently facing an issue with the formatting of a chunk of text which is retrieved from a webserver as a JSON array.
What I am trying to acomplish is to format the text in a way that can be easily read by the user. An Example output of what I am trying to achieve is:
This is a Title
This is a little informative paragraph based on the subject selected
This is a secondary title
This is another paragraph
The way the string looks (before modification):
{"Title":"This is a Title", "Content_One": "This is alittle
informative paragraph based on the subject selected", "Title_Two":
"This is another paragraph"}
My current application is using Winforms, and I'm attempting to pump this into a Rich Text Box (hopefully going to handle the correct formatting). As a little long shot, I tried returning HTML Tags (Very long shot) For this to provide no change to the text.
I have also tried individually iterating through the array, and attempting to pramatically bold out certain elements from the JSON Array. None of which I have tried have provided expected output.
Attempt one:
TTKNormalContent.Text = new Font(ReturnArr.Title, FontStyle.Bold).ToString();
Which returns:
An unhandled exception of type
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll
Attempt one:
TTKNormalContent.Text = ReturnArr.Title;
TTKNormalContent.SelectionFont = new Font(this.Font, FontStyle.Bold);
Which does not bold out the text
Attempt Two:
I can temporarily make the text bold by:
TTKNormalContent.Font = new Font(TTKNormalContent.Font, FontStyle.Bold);
TTKNormalContent.Text = ReturnArr.Title;
But adding:
TTKNormalContent.Font = new Font(TTKNormalContent.Font, FontStyle.Regular);
TTKNormalContent.Text += ReturnArr.ContentOne;
Which will remove the boldness
You need to use AppendText. When you use Text+= "something" you replace the format.
You can use this example:
var json = "{\"Title\":\"This is a Title\", \"Content_One\": \"This is alittle informative paragraph based on the subject selected\", \"Title_Two\": \"This is another paragraph\"}";
var start = 0;
Dictionary<string, string> values = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(json);
values.Cast<KeyValuePair<string, string>>()
.ToList()
.ForEach(item =>
{
this.richTextBox1.AppendText(item.Key);
this.richTextBox1.AppendText( ":" );
start += item.Key.Length + 1;
this.richTextBox1.AppendText(item.Value);
this.richTextBox1.Select(start, item.Value.Length);
this.richTextBox1.SelectionFont = new Font(this.richTextBox1.Font, FontStyle.Bold);
this.richTextBox1.AppendText("\n");
start += item.Value.Length + 1;
});
Screenshot:

Why TrimStart is working only when i assign the text again back th the variable?

scrollerList = new List<string>(TextExtractor.newTextWithoutLinks);
scrollerText = string.Join(Environment.NewLine, scrollerList);
combindedString = string.Join(Environment.NewLine, newText);
scroller1.TextToScroll = scrollerText;
richTextBox1.Text = combindedString;
richTextBox1.Text = richTextBox1.Text.TrimStart();
richTextBox1.Refresh();
This is a working line:
richTextBox1.Text = richTextBox1.Text.TrimStart();
But if i'm doing:
richTextBox1.Text.TrimStart();
It's not working i mean dosen't make any changes.
Not that i'm getting any exceptions but a bit strange i need to assign twice to the richTextBox1 the text to delete the empty line at the top of the richTextBox1.
string is immutable - what you're seeing is expected behaviour. Operations like TrimStart() will create a new string, which is returned when calling that method.
Why not do it in one go?
richTextBox1.Text = combindedString.TrimStart();
TrimStart() returns a new string with the values trimmed. It does not modify the original string:
From http://msdn.microsoft.com/en-us/library/system.string.trimstart(v=vs.110).aspx
This method does not modify the value of the current instance.
Instead, it returns a new string in which all leading white space
characters found in the current instance are removed.
It generates a new string, which has nothing to do with the old one. You have to replace the existing one with the new one!
So this is right:
richTextBox1.Text = richTextBox1.Text.TrimStart();

How to affect formatting of dynamically created label text in c#

I think this should be a pretty easy question to answer but I can't seem to figure it out.
I am adding text to labels from a sqldatasource in c#. All of that works, but I want to be able to format the text. I want to 1) be able to change the format to 0.00 (instead of a string of decimals) and I would also like to be able to add words before the text. I assume I need to somehow use the string.format command but can't figure out how to work it in. Any help would be greatly appreciated. Here's my code below:
DataView dvSql = (DataView)DeskSummary.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drvSql in dvSql)
{
Desk.Text = drvSql["Deskname"].ToString();
MarginLabel.Text = drvSql["margin"].ToString();
CurrentCI.Text = drvSql["comp_index_primarycomp"].ToString();
WalMartCurrentCI.Text = drvSql["comp_index_walmart"].ToString();
ForecastMargin.Text = drvSql["margin_forecast"].ToString();
WalMartForecastCI.Text = drvSql["comp_index_walmart_forecast"].ToString();
ForecastCI.Text = drvSql["comp_index_primarycomp_forecast"].ToString();
}
You can pass the format argument to the ToString() method like so:
MarginLabel.Text = drvSql["margin"].ToString("0.00");
However, as you said you wanted to prepend some text. Therefore, I recommend:
MarginLabel.Text = String.Format("Prepended text {0:0.00}", drvSql["margin"]);
Note: I just picked one of your labels; I'm not sure which ones get special formatting treatment.
use the
string.Format("This is a before text {"0"},your param)
// you can add as many variables and {""} string literals as you need just make sure that you separate the variables with a ","
Here is the code
string stringNumber = "5123.34214513";
decimal decimalNumber = Decimal.Parse(stringNumber);
string output = String.Format("Your text: {0:0.00}", decimalNumber);
Console.WriteLine(output); //Your text: 5123.34
This works if the column is of type string
String.Format() will do what you need for prepending/appending text values,
string.Format("prepend text {"0"} append text", paramString)
But if you want to actually format the value you are getting back from SQL, then you would need to use String.Format() on that value as well as possibly some RegEx expressions and/or .ToUpperCase or .ToLowercase for your capitalization... something like.
var capitalizedString = paramString.subStr(0,1).ToUppercase + paramString.subStr(1, paramstring.Length);
string.Format("Prepended text {"0"} plus appended text", capitalizedString);

Categories

Resources