im trying to make some kind of search function in my program which is just highlighting all keywords found on textbox
the keyword box is on t2.text and the text is from bx2.text
firstly i tried out this method from here Highlight key words in a given search text
the regex is working but the highlight not
any wrong here?
private void searchs()
{
var spattern = t2.Text;
foreach(var s in bx2.Text)
{
var zxc = s.ToString();
if (System.Text.RegularExpressions.Regex.IsMatch(zxc, spattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
bx2.Text.Replace(bx2.Text, #"<span class=""search-highlight"">$0</span>");
}
}
}
The linked question uses HTML formatting, which you can't use in a regular textbox.
You need either a RichText box. In there you can format text using the control's methods and properties (not using HTML).
Or use a browser control rather than a textbox to use the HTML formatting.
private void findButton_Click(object sender, EventArgs e)
{
int count = 0;
string keyword = keywordTextbox.Text.Trim();//getting given searching string
int startPosition = 0; //initializing starting position to search
int endPosition = 0;
int endArticle = articleRichTextbox.Text.Length;//finding total number of character into the article
for (int i = 0; i<endArticle ; i =startPosition )//creating a loop until ending the article
{
if (i == -1) //if the loop goes to end of the article then stop
{
break;
}
startPosition = articleRichTextbox.Find(keyword, startPosition, endArticle, RichTextBoxFinds.WholeWord);//using find method get the begining position when find the searching string
if (startPosition >= 0) //if match the string //if don't match the string then it return -1
{
count++;//conunting the number of occuerence or match the search string
articleRichTextbox.SelectionColor = Color.Blue;//coloring the matching string in the article
endPosition = keywordTextbox.Text.Length;
startPosition = startPosition + endPosition;//place the starting position at the next word of previously matching string to continue searching.
}
}
if (count == 0)//if the givn search string don't match at any time
{
MessageBox.Show("No Match Found!!!");
}
numberofaccurTextbox.Text = count.ToString();//show the number of occurence into the text box
}
Related
I'm trying to move the first char of the string to the end every time I press the button.
My logic seems to only display the first output again and again after I press the button.
string input = "";
string manipulated = "";
int initial;
input = txtInput.Text;
if (txtInput.Text == String.Empty)
{
MessageBox.Show("Textbox is empty, please input a string.");
}
else
{
for (initial = 1; initial < input.Length; initial++)
{
manipulated += input[initial];
}
manipulated += input[0];
lblOutput.Text = manipulated.ToString();
input = manipulated;
manipulated = "";
}
E.g. if I enter "1234" in the text box and press the button, my output should be "2341", then after I hit the button again, the output should move to "3412" .. etc.
This is a simple example of Basics String operations:
private void ManipulateBtn_Click(object sender, EventArgs e)
{
string input = InputTxt.Text; // Read the text from you Textbox in Windos form
if (input == string.Empty)
{
return;
}
string temp = input[0].ToString(); // Create a temp for the first char(toString) from you input
input = input.Remove(0,1); // Remove (from you input) At Index 0 (the idex from fist char in string) 1 time)
input += temp; //add the firs item from you input at the end of string
InputTxt.Text = input; // prin the result in the Textbox back.
}
You can see the example SimpleStringOperation
You can Improve your code by another solution using Substring Method
Create a new variable called _number and set the value to 1
public partial class Form1: Form
{
private int _number = 1;
// ....
}
Then in Button event, you can replace your code with this code
private void BtnMoveText_Click(object sender, EventArgs e)
{
if (txtInput.Text == string.Empty)
{
MessageBox.Show(#"TextBox is empty, please input a string.");
return;
}
if (_number > txtInput.TextLength)
_number = 1;
lblOutput.Text = txtInput.Text.Substring(_number) + txtInput.Text.Substring(0, _number);
_number++;
#region ** Depending on Microsoft **
/*
Substring(Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
.......................
Substring(Int32, Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length..)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
length Int32
The number of characters in the substring.
*/
#endregion
}
You're taking your OUTPUT and placing it in a Label...but continuing to take your INPUT from the TextBox which hasn't changed...thus the same result each time.
Simply change:
lblOutput.Text = manipulated.ToString();
To:
txtInput.Text = manipulated;
I want to make a clickable text through code in c# (its not a URL just ordinary text) so when i click that text it do linkclicked event.
It is for a dictionary so when I search something and in the description there is a word same from the storage I can click it to search that word.
for (int j = 0; j <= jml[i]; j++)
{
richTextBox4.AppendText(j + 1 + ". ");
string[] desk = sk[i, j].Split(' ');
for (int l = 0; l < desk.Count(); l++)
{
for (int m = 0; m < kata.Count(); m++)
{
if (desk[l] == kata[m])
{
richTextBox4.SelectionColor = Color.Blue;
desk[l] = LinkArea;
}
}
richTextBox4.AppendText(desk[l] + " ");
richTextBox4.SelectionColor = Color.Black;
}
richTextBox4.AppendText("\n");
}
my code for the moment(for the hyperlink type text just the color that work)
There is no built-in way but if you know what you want it is not hard to build.
Step one is to decide just how the clickable text is defined, read: What are the separators?
If you want single words it is rather easy. One way is using a regEx to identify words in a RTB. If you don't like the built-in way to define a word, I can post a code with user-defined separators.. But maybe you are happy with what have already.
If you need whole phrases (including spaces) to be clickable as one whole entity then you will have to be a little more inventive:
either you can add special characters around the phrases
or you can replace the spaces by non-breakable spaces
Or you could write a complete map into your text, but that probably defies your purpose.
Anything but simple words will mean that you will need to apply some changes to your text.
The result should be a function that can find the start and the end of the clickable text and return the clicked word/phrase.
Step Two is to look up the text in a Dictionary<string, string> and do what you want to do with the value, e.g. show the translation in a Label:
if (dictEnGE.ContainsKey(theClickedWord))
label.Text = dictEnGE[theClickedWord];
For this to work you must first prepare the dictionary by adding the key-value pairs: The keys are the clickable texts and the values are whatever you need to find:
Dictionary<string, string> dictEnGE = new Dictionary<string, string>();
dictEnGE.Add("house", "Haus");
dictEnGE.Add("man", "Mann");
dictEnGE.Add("mouse", "Maus");
//..
So the whole solution is: Prepare a dictionary, code the Mouseclick event to find the clicked text, look up the text in the dictioanry, do your thing with the value you find..
Update: Here is a function to get the clicked word:
string getWordAtIndex(RichTextBox RTB, int index)
{
string wordSeparators = " .,;-!?\r\n\"";
int cp0 = index;
int cp2 = RTB.Find(wordSeparators.ToCharArray(), index);
for (int c = index; c > 0; c--)
{ if (wordSeparators.Contains(RTB.Text[c])) { cp0 = c + 1; break; } }
int l = cp2 - cp0;
if (l > 0) return RTB.Text.Substring(cp0, l); else return "";
}
and here is how you could use it:
private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
{
string word = getWordAtIndex(richTextBox1, richTextBox1.SelectionStart);
if (dictEnGE.ContainsKey(word)) aLabel.Text = dictEnGE[word];
}
I have a problem while trying to replace all text matching a particular word in a rich text box. This is the code i use
public static void ReplaceAll(RichTextBox myRtb, string word, string replacer)
{
int index = 0;
while (index < myRtb.Text.LastIndexOf(word))
{
int location = myRtb.Find(word, index, RichTextBoxFinds.None);
myRtb.Select(location, word.Length);
myRtb.SelectedText = replacer;
index++;
}
MessageBox.Show(index.ToString());
}
private void btnReplaceAll_Click(object sender, EventArgs e)
{
Form1 text = (Form1)Application.OpenForms["Form1"];
ReplaceAll(text.Current, txtFind2.Text, txtReplace.Text);
}
This works well but i have noticed a little malfunction when i try to replace a letter with itself and another letter.
For example i want to replace all the e in Welcome to Nigeria with ea.
This is what i get Weaalcomeaaaaaaa to Nigeaaaaaaaaaaaaaaria.
And the message box shows 23 when there are only three e. Pls what am i doing wrong and how can i correct it
Simply do this:
yourRichTextBox.Text = yourRichTextBox.Text.Replace("e","ea");
If you want to report the number of matches (which are replaced), you can try using Regex like this:
MessageBox.Show(Regex.Matches(yourRichTextBox.Text, "e").Count.ToString());
UPDATE
Of course, using the method above has expensive cost in memory, you can use some loop in combination with Regex to achieve some kind of advanced replacing engine like this:
public void ReplaceAll(RichTextBox myRtb, string word, string replacement){
int i = 0;
int n = 0;
int a = replacement.Length - word.Length;
foreach(Match m in Regex.Matches(myRtb.Text, word)){
myRtb.Select(m.Index + i, word.Length);
i += a;
myRtb.SelectedText = replacement;
n++;
}
MessageBox.Show("Replaced " + n + " matches!");
}
I want to check file content for a particular string, actually I want to check is file contains 'ANSWER' and if there some character of anything after that string to the end of file.
How can I achive that?
p.s. file content is dynamic content and that 'ANSWER' string is not on fixed location inside file.
Thanks
static bool containsTextAfter(string text, string find)
{
// if you want to ignore the case, otherwise use Ordinal or CurrentCulture
int index = text.IndexOf(find, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
int startPosition = index + find.Length;
if (text.Length > startPosition)
return true;
}
return false;
}
use it in this way:
bool containsTextAfterAnswer = containsTextAfter(File.ReadAllText("path"), "ANSWER");
One way is to load the entire file into memory and search it:
string s = File.ReadAllText(filename);
int pos = s.IndexOf("ANSWER");
if (pos >= 0)
{
// we know that the text "ANSWER" is in the file.
if (pos + "ANSWER".Length < s.Length)
{
// we know that there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" doesn't exist in the file.
}
Or, you can use a regular expression:
Match m = Regex.Match(s, "ANSWER(.*)");
if (m.Success)
{
// the text "ANSWER" exists in the file
if (m.Groups.Count > 1 && !string.IsNullOrEmpty(m.Groups[1].Value))
{
// there is text after "ANSWER"
}
}
else
{
// the text "ANSWER" does not appear in the file
}
In the regex case, the position of "ANSWER" would be in m.Index, and the position of the text after "ANSWER" would be in m.Groups[1].Index.
I am working with windows form. In my project i need to color the last word of rich text box. When someone write on the given text box of the application i need the last word that is just written on the richtextbox to be colored red or whatever.
I found a way to extract the last word from the following link
http://msdn.microsoft.com/en-us/library/system.windows.documents.textselection.select%28v=vs.95%29.aspx
But i need more handy code to extract the last word if its possible. Please help.
Well, if you really are just looking to get the last word, you could do something like this...Assuming of course, that you make a string equal to the text of your rich text box.
string str="hello, how are you doing?";
if (str.Length >0)
{
int index=str.LastIndexOf(" ") + 1;
str = str.Substring(index));
}
Then just return the string, and do what you need to do with it.
Here is the sample code
*> char[] arr = new char[50];
int i = 0;
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space) {
string str = new string(arr);
MessageBox.Show(str);
Array.Clear(arr, 0, arr.Length);
i = 0;
}
else if (e.KeyCode == Keys.Back)
{
i--;
if (i < 0)
{
i = 0;
}
arr[i] = ' ';
}
else
{
arr[i] = (char)e.KeyValue;
i++;
}
}*
This is how you will be able to extract the latest word. Now color yourself the word you like.
As I remember rich text box can render text as HTML.
Just wrap your last word in font tag and that's it.