Get TextBox line number - c#

I want to get a TextBox lines number in C# winform application. But unlike this question I want the real line number, whether it is a wrapped line or is a new line with \r\n.
var lines = tb.Lines.Count(); will just get the lines number with carriage return.
So How can I get what I'm looking for?

I dont understand what you want, but generally you can use this code to count lines in your textbox:
public int LineNumber()
{
int LineNumber;
LineNumber = textBoxNotePad.Lines.Length;
return LineNumber;
}
I hope it's useful

Related

Search text file for text above which pattern matches input

I am trying to make my program display the text above the input text which matches a pattern I set.
For example, if user input 'FastModeIdleImmediateCount"=dword:00000000', I should get the closest HKEY above, which is [HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000] for this case.
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]
"StandardModeIdleImmediateCount"=dword:00000000
"FastModeIdleImmediateCount"=dword:00000000
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD\DEVICE0]
"Attach.ToDesktop"=dword:00000001
Could anyone please show me how I can code something like that? I tried playing around with regular expressions to match text with bracket, but I am not sure how to make it to only search for the text above my input.
I'm assuming your file is a .txt file, although it's most probably not. But the logic is the same.
It is not hard at all, a simple for() loop would do the trick.
Code with the needed description:
string[] lines = File.ReadAllLines(#"d:\test.txt");//replace your directory. We're getting all lines from a text file.
string inputToSearchFor = "\"FastModeIdleImmediateCount\"=dword:00000000"; //that's the string to search for
int indexOfMatchingLine = Array.FindIndex(lines, line => line == inputToSearchFor); //getting the index of the line, which equals the matchcode
string nearestHotKey = String.Empty;
for(int i = indexOfMatchingLine; i >=0; i--) //looping for lines above the matched one to find the hotkey
{
if(lines[i].IndexOf("[HKEY_") == 0) //if we find a line which begins with "[HKEY_" (that means it's a hotkey, right?)
{
nearestHotKey = lines[i]; //we get the line into our hotkey string
break; //breaking the loop
}
}
if(nearestHotKey != String.Empty) //we have actually found a hotkey, so our string is not empty
{
//add code...
}
You could try to split the text into lines, find the index of the line that contains your text (whether exact match or regex is used doesn't matter) and then backsearch for the first key. Reverse sorting the lines first might help.

Searching for a phrase in text file then displaying that line

im trying to make a code that searches through a textfile for a certain phrase and then populates a textbox with the line if a phrase occurs in that. There are no errors with this code, but it doesn't work at all. Anyone know what is wrong? I'm not too sure if what i'm doing is remotely correct.
{
tuitDisplayTextBox.Text = "";
string[] tuitFilePath = File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
for (int i = 0; i < tuitFilePath.Length; i++)
{
if (tuitFilePath[i].Contains(searchTextBox.Text))
{
tuitDisplayTextBox.Text += tuitFilePath[i];
}
}
Your solution should work... for the last line that matches, and only that one.
LINQ can help you here, though. Here's a solution that should work.
tuitDisplayTextBox.Text =
File.ReadLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt")
.Where(n => n.Contains(searchTextBox.Text)).Aggregate((a, b) =>
a + Enviroment.NewLine + b);
Here, what it does is it reads the lines of the file into an IEnumerable<string>, and then I filter that with the Where method, which basically means "if the condition is true for this element, add this element to the list of things to return, else don't add it". And then Aggregate is a bit more complicated. Basically what it does is it takes the first two items from the collection, and then pass a lambda through them that returns a value. Then call the lambda again with that result and the third element. And then it takes that result and calls it with the fourth element. And so on.
Here's some code more similar to yours that will also work:
tuitDisplayTextBox.Text = "";
IEnumerable<string> lines =
File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
StringBuilder sb = new StringBuilder
foreach (string line in lines)
{
if (line.Contains(searchTextBox.Text))
{
sb.AppendLine(line);
}
}
tuitDisplayTextBox.Text = sb.ToString();
Here it's a bit different. First it reads all the lines into an IEnumerable<string> called lines. Then it makes a StringBuilder object (basically a mutable string). After that, it foreaches the lines in the IEnumerable<string> (I thought it was more appropriate here) and then if the line contains the text you want, it adds that line and a newline to the StringBuilder object. After that, it sets your textbox's text to the result of all of that, by getting the string representation of the StringBuilder instance.
And if you really want a for loop, here's the code modified to use a for loop:
tuitDisplayTextBox.Text = "";
string[] lines =
File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
StringBuilder sb = new StringBuilder
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(searchTextBox.Text))
{
sb.AppendLine(lines[i]);
}
}
tuitDisplayTextBox.Text = sb.ToString();
Please note that File.ReadAllLines break sentences at '\r' or '\n'.
So, if you search for "hello world" and this text is break in the file into 2 lines (e.g. "... hello /n world" your code will failed...
So, use the ReadAllText() instead, return one string contains all file's text.
Still, you might face sometimes problems with file encoding, but this is another issue.
After, and if, you find the text you are searching for you can use the ReadAllLines to decide about the location of the text.

Weird string behaviour, replaces parts of itself

I can't seem to wrap my head around this. How can this become:
string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex);
this:
/3?dl=1/www.dropbox.com/s/s8ghw2mvld2jg0l
It's like taking the part after {0} ,shifts it to the front and overrides the existing string...
Does anyone know what's going on here?
This is the entire code (pseudo):
string[] dl = new string[] { "...", "...", "..." };
int rndIndex = rnd.Next(0, dl.Length);
Console.WriteLine(string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex));
There's nothing wrong with dl[] and rndIndex, checked both of them.
This fixed the problem:
string s = dl[rndIndex];
s = s.Replace(((char)13).ToString(), "");
Which is what you suggested.
The way the it replaces the beginning of the URL, it seems that dl[rndIndex] contains a carriage return which places the cursor back to the beginning of the line and then overwrites the https:/ part of the URL (which fits as /3?dl=1 has the same length).
So your formatted string actually looks like this:
"https://www.dropbox.com/s/s8ghw2mvld2jg0l\r/3?dl=1"
^^
carriage return
Now when that is printed to a console which supports carriage returns, it will print the first part https://www.dropbox.com/s/s8ghw2mvld2jg0l then set the cursor back to the beginning and print the rest /3?dl=1.
So you should basically strip out all carriage returns from the string first. In any way it seems as if your dl array does not contain what you expect it to do.
I can reproduce the exact problem by #poke's comment:
string.Format("https://www.dropbox.com/s/{0}/{1}?dl=1", "hfjdhfjdh\r", 30)
will output:
/30?dl=1www.dropbox.com/s/hfjdhfjdh
The problem is a carriage return or new line character in your array elements.
Modifying your fragment as follows:
string[] dl = new string[] { "...", "...", "..." };
int rndIndex = 1; // rnd.Next(0, dl.Length);
Console.WriteLine(string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex));
Gives a correct answer.
https://www.dropbox.com/s/.../1?dl=1
So, two thoughts:
It's a data dependent problem
Should the random function not read rnd.Next(0, dl.Length-1)

C# WinForms - Adding text to each line in a textbox

I am very new to C#. I learn best by experimentation, but of course, I will get completely stumped sometimes. I will try to explain my problem the best I can with what knowledge of the programming language I currently have.
I have been trying to create a simple tool to edit/add lines of text into a text file. I have done much researching, especially on this site, and all the information has been extremely helpful. My problem though, is adding text to both sides to a single line of text within a multi-line textbox.
So lets say I have a textbox with 2 existing lines; I want to add some text next to both sides of to one of one lines, and do the same to the next one. Here is an example of what the text would look like before and after a button is hit:
Before
is not the same as is different than
After
A is not the same as B A is different than B
The two lines in "Before" would be in textBox1 (multiline), and would be inserted to richTextBox1 as "After".
Hopefully I have explained it clearly enough, I do not know where to begin with this.
Thank you.
If you know which index you have to update the text, then you should be able to inset the value directly using insert function exposed by string class
Example:
//Get the text box value
var formatedTextboxString = this.textbox1.Text;
formatedTextboxString = formatedTextboxString.Insert(0, "A ");
formatedTextboxString = formatedTextboxString.Insert(21, "B");
//Place the formated text back to the richTextBox
this.richTextBox1.Text = formatedTextboxString;
Try
"{0} is not the same as {1} {2} is different than {3}"
In textbox1. Then use:
textbox2.Text = String.Format(textbox1.Text, A, B, A, B);
In case if you have multiline textbox:
var list = new List<string>(textBox1.Lines);
for (int i = 0; i < list.Count; ++i)
{
list[i] = "A" + list[i] + "B";
}
textBox1.Lines = list.ToArray();
string[] arr = textBox1.Text.Split(Environment.Newline);
//then loop over each line and add whatever you want :-
foreach (string s in arr)
{
//add here
}
I guess this is good enough hint to start with :)

Multiline TextBox with custom word wrapping

I am beginning to program in .Net and C# and currently I am stuck. I have a very similar problem as the posting on this question at stackoverflow : C#: Multiline TextBox with TextBox.WordWrap Displaying Long Base64 String.
The response to that question was this block of code:
public IEnumerable<string> SimpleWrap(string line, int length)
{
var s = line;
while (s.Length > length)
{
var result = s.Substring(0, length);
s = s.Substring(length);
yield return result;
}
yield return s;
}
I dont know how to make use of that piece of code. CAn someone please provide me with a code snippet that uses this particular method to write text that automatically also inserts a new line.
My code currently looks like this:
var length = GetMaximumCharacters(txtBxResults);
var txtWrap = SimpleWrap(stringValue, length);
foreach (string s in txtWrap)
{
txtBxResults.AppendText(s);
}
If I use AppendText method, it simple writes all the text in one single line which I do not want.
Any replies will be greatly appreciated.
Thanks,
KK
You almost have it right, you just need to insert the newline character as well. Try
foreach (string s in txtWrap)
{
txtBxResults.AppendText(s + Environment.NewLine);
}
Well I can't give you the exact code right now (I'll come back and post it later) but in general, what you should do is identify the index of the next comma and, if characters on the current line + that index > length of the line then append a new line before that compound. If you do that in a bucle, when it's done it should be formatted correctly, also take into account the last compound won't have (I think) a comma at the end.

Categories