Hi,

it have written a notepad application in C# 2008 which i am using to open documents with a lot of lines for example 5000+ lines. the problem that i have is that i have created a button that i want to use to select a specific number of lines. For example if i have a document that contains 5000 lines, i want to be able to select 3000 when i press the button. Then i can cut or copy the highlighted lines. This is the code i use to count the number of lines

Int32 lines = richTextBox1.Lines.Length;
Int32 textLength = richTextBox1.Text.Length;
statusLabel.Text = "Lines: " + lines + " Characters: " + textLength;

Thank you for your help in advance

Here you are

/* \r\n or just \n depending from where you got data text file or something esle \r*/
string[] lines = richTextBox1.Text.Split(new string[]{"\r\n"}, StringSplitOptions.None);
//you need, say to select first 3000 lines
for(int i=0; i<3000; i++)
{
richTextBox1.Append(lines[i]);
}

splitting the lines up manually is no longer required. dotnet3.5 has the lines array member of the ritchtextbox control. so it works to just call that..

as for the selecting of lines, you can only select using the start number of the charter, so we can easily use built in functions of the ritchtextbox control to do this all for us. I created two variables and hardcoded them to some easy for testing line numbers, but just set thoes values to a number parsed from a textbox or something to get the dynamic effect you are looking for.

Here is the completed working code, assuming you are using a ritchtextbox control, named ritchtextbox1.

int firstlinenumber = 2;//set this to the line number to start selection with.
            int endlinenumber = 3;// set this to line number to end slection with.
            int selectstart = richTextBox1.GetFirstCharIndexFromLine(firstlinenumber-1);
            int selectend = richTextBox1.GetFirstCharIndexFromLine(endlinenumber-1) + richTextBox1.Lines[endlinenumber-1].Length;
            int selectlenght = selectend - selectstart;
            richTextBox1.Focus();//important. you cant select when the
             //textbox doesn't have focus. so focus it before you select
            richTextBox1.Select(selectstart, selectlenght);

important to note: this can be done the same way in fewer lines, just condensed. I tried to spread it out, so it made more sense of how it works. Its important to learn!

happy coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.