In RichTextBox, I'm trying to fire an event with pressing period ('.') But It's not working for the first time.
If I write "Lorem Ipsum.", It's not working but If I write "Lorem Ipsum ." or "Lorem Ipsum.." It's OK.
PS: I've added the KelimeGuncelle method and GetWordGroupInstances() dictionary also.
Here's the block:
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
kelimeGuncelle();
}
}
The kelimeGuncelle method:
void kelimeGuncelle()
{
Dictionary<String, int> TekliKelimeGruplari = GetWordGroupInstances(1);
foreach (var item in TekliKelimeGruplari)
{
for (int i = 0; i < lstKelimeler.Items.Count; i++)
{
var kelime = lstKelimeler.Items[i];
string guncellenecekKelime = kelime.ToString().Remove(kelime.ToString().IndexOf(" ( ") - 1);
string gelenKelime = item.Key;
string _guncellenecekKelime = kelime.ToString();
int pFrom = _guncellenecekKelime.IndexOf("(") + 1;
int pTo = _guncellenecekKelime.LastIndexOf("/");
int guncellenecekSayi = Convert.ToInt32(_guncellenecekKelime.Substring(pFrom, pTo - pFrom));
int kFrom = _guncellenecekKelime.IndexOf("/") + 1;
int kTo = _guncellenecekKelime.LastIndexOf(")");
int toplamYazilacakSayi = Convert.ToInt32(_guncellenecekKelime.Substring(kFrom, kTo - kFrom));
int kelimeninSirasi = lstKelimeler.Items.IndexOf(kelime);
if (Equals(guncellenecekKelime, gelenKelime))
{
guncellenecekSayi = item.Value;
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( " + guncellenecekSayi + "/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
if (rtbMakale.Text.Contains(guncellenecekKelime) == false)
{
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( 0/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
}
}
TekliKelimeGruplari.Clear();
}
And GetWordGroupInstances:
Dictionary<String, int> GetWordGroupInstances(int GroupSize)
{
Dictionary<String, int> WordGroupInstances = new Dictionary<string, int>();
String[] sourceText = GetSourceText().Split(' ');
int pointer = 0;
StringBuilder groupBuilder = new StringBuilder();
while (pointer < sourceText.Length - GroupSize)
{
groupBuilder.Clear();
int offset = pointer + GroupSize;
for (int i = pointer; i < offset; i++)
{
groupBuilder.Append(" ").Append(sourceText[i]);
}
String key = groupBuilder.ToString().Substring(1);
if (!WordGroupInstances.ContainsKey(key))
{
WordGroupInstances.Add(key, 1);
}
else
{
WordGroupInstances[key]++;
}
pointer += 1;
}
return WordGroupInstances;
}
try using a MessageBox.Show("Test"); for testing , maybe something in your kelimeGuncelle() method is wrong.
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
MessageBox.Show("Test");
}
}
I got it!
In the GetWordGroupInstances, I've changed the while loop. Here:
while (pointer <= sourceText.Length - GroupSize)
Related
I created a program that uses both linear and binary search method. I use string array.
private void linearSearch_Click(object sender, EventArgs e)
{
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
this will work, however the binary doest not
private void BinarySearch_Click(object sender, EventArgs e)
{
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if(numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target+ " is at index: " + numIndex;
}
}
test1 test2
Note that the code is performing a binary search in the text box of binarySearchBox, not the value in the text box of ListBox1.
The code that needs to convert the value added to ListBox1 into an Array array for storage.string[]myArray = listBox1.Items.Cast<string>().ToArray();,then search for ListBox1.
Code show as below:
private void BinarySearch_Click(object sender, EventArgs e)
{
string[]myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if (numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target + " is at index: " + numIndex;
}
}
private void linearSearch_Click(object sender, EventArgs e)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
I am looking to store values from a CSV file with two Columns, I have the following class ReadFromCSVhandling the reading of the CSV file but I am having difficulty using this list to display the contents once a button is clicked. The code I have to read the CSV file is as follows;
namespace ELMFS
{
public class ReadFromCSV
{
static void ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
}
}
public class TextSpeak
{
string Abreviated;
string Expanded;
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
I am trying to display the textSpeak.Abreviated in a message box but cannot seem to access it from the WPF window.
How do I use this list in other windows within the application?
any advice would be appreciated!
Thanks in advance!
First, ReadCSV method should return the generated List object (or you cannot use the list anywhere else).
Second, TextSpeak class should have properties so that you can access its member variables outside the class.
I.e. something like this should work:
namespace ELMFS
{
public class ReadFromCSV
{
public static List<TextSpeak> ReadCSV(string[] args)
{
List<TextSpeak> TxtSpk = File.ReadAllLines(#"C:\textwords.csv")
.Skip(1)
.Select(t => TextSpeak.FromCsv(t))
.ToList();
return TxtSpk;
}
}
public class TextSpeak
{
public string Abreviated { get; private set; }
public string Expanded { get; private set; }
public static TextSpeak FromCsv(string csvLine)
{
string[] TxtSpk = csvLine.Split(',');
TextSpeak textSpeak = new TextSpeak();
textSpeak.Abreviated = TxtSpk[0];
textSpeak.Expanded = TxtSpk[1];
return textSpeak;
}
}
}
private void Display(int count)
{
textBox1.Text = "";
for (int i = 0; i <= count ; i++)
{
textBox1.Text += ((dataGridView1.Rows[i].Cells[1].Value).ToString()) + (dataGridView1.Rows[i].Cells[2].Value.ToString()) + Environment.NewLine;
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// your code here
string CSVFilePathName =Path.GetDirectoryName(Application.ExecutablePath).Replace(#"\bin\Debug", #"\NewFolder1\TEST.csv");
string[] Lines = File.ReadAllLines(CSVFilePathName);
string[] Fields;
Fields = Lines[0].Split(new char[] { ',' });
int Cols = Fields.GetLength(0);
DataTable dt = new DataTable();
//1st row must be column names; force lower case to ensure matching later on.
for (int i = 0; i < Cols; i++)
dt.Columns.Add(Fields[i].ToLower(), typeof(string));
DataRow Row;
for (int i = 1; i < Lines.GetLength(0); i++)
{
Fields = Lines[i].Split(new char[] { ',' });
Row = dt.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dt.Rows.Add(Row);
}
dataGridView1.DataSource = dt;
int count = 0;
if (dataGridView1.RowCount > 0)
{
count = dataGridView1.Rows.Count;
}
buttons = new Button[count];
for (int i = 0; i <count; i++)
{
buttons[i] = new Button();
buttons[i].Name = "buttons_Click" + i.ToString();
buttons[i].Text = "Click";
buttons[i].Click += new EventHandler(buttons_Click);
this.Controls.Add(buttons[i]);
buttons[i].Visible = false;
}
buttons[0].Visible = true;
// buttons[1].Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Error is " + ex.ToString());
throw;
}
}
private void buttons_Click(object sender, EventArgs e)
{
int count = dataGridView1.Rows.Count-1;
if(c <= count)
{
if (buttons[c].Name == "buttons_Click" + c.ToString())
{
buttons[c].Visible = false;
int j = c;
Display(j);
if (c != count)
{
c = c + 1;
buttons[c].Visible = true;
}
}
}
if (c == count)
{
buttons[0].Visible = true;
}
}
}
}
I have a program where i need to count how many females and Males are in the file that has been read into the richtextbox, but I'm not sure how to do that , in the file has the name, gender,specific job . I have to count between 15 different people
for example : " Donna,Female,Human Resources.",
This is what I have so far:
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr;
richTextBox1.Clear();
sr = new StreamReader("MOCK_DATA.txt");
string data;
while (!sr.EndOfStream)
{
data = sr.ReadLine();
richTextBox1.AppendText(data + "\n");
}
}
private void button1_Click(object sender, EventArgs e)
{
string[] data = richTextBox1.Text.Split(',');
for (int n = 0; n < data.Length; n++)
{
if (data[n] == richTextBox1.Text)
n++;
To get the plain text from a RichTextBox (stolen from this article):
string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(
// TextPointer to the start of content in the RichTextBox.
rtb.Document.ContentStart,
// TextPointer to the end of content in the RichTextBox.
rtb.Document.ContentEnd
);
// The Text property on a TextRange object returns a string
// representing the plain text content of the TextRange.
return textRange.Text;
}
Basic word counting routine:
int CountWord(string textToSearch, string word)
{
int count = 0;
int i = textToSearch.IndexOf(word);
while (i != -1)
{
count++;
i = textToSearch.IndexOf(word, i+1);
}
return count;
}
Putting it together:
var plainText = StringFromRichTextBox(richTextBox1);
var countOfMale = CountWord(plainText, "Male");
var countOfFemale = CountWord(plainText, "Female");
private void toolStripButton81_Click(object sender, EventArgs e)
{
string findterm = string.Empty;
findterm = toolStripTextBox2.Text;
// the search term - specific word
int loopCount = 0;
// count the number of instance
int findPos = 0;
// depending on checkbox settings
// whole word search or match case etc
try
{
while (findPos < GetRichTextBox().Text.Length)
{
if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked & matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
}
else if (wholeWordToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.WholeWord);
}
else if (matchCaseToolStripMenuItem.CheckState == CheckState.Checked)
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.MatchCase);
}
else
{
findPos = GetRichTextBox().Find(findterm, findPos, RichTextBoxFinds.None);
}
GetRichTextBox().Select(findPos, toolStripTextBox2.Text.Length);
findPos += toolStripTextBox2.Text.Length + 1;
loopCount = loopCount + 1;
}
}
catch
{
findPos = 0;
}
// at the end bring the cursor at the beginning of the document
GetRichTextBox().SelectionStart = 0;
GetRichTextBox().SelectionLength = 0;
GetRichTextBox().ScrollToCaret();
// Show the output in statusbar
toolStripStatusLabel2.Text = "Instances: " + loopCount.ToString();
}
This code i used to text change as i need.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
A = A.Replace("A", "C");
A = A.Replace("F", "H");
A = A.Replace("C", "W");
A = A.Replace("B", "G");
textBox2.Text = (A);
}
Now i need to stop text changing after,
if i type '|' symbol in tetxbox1, Again i need to
start text changing if i type '|' symbol again,such as happened thing in this image.
So how can i prevent text changing between these two symbols only ||
You're replace code won't work how you have it, as it will just keep changing the characters for the same string(you change A to C, and later down you change C to W, so your final first character would be W and not C like you want).
Below is an overly complicated method(i also added a method that runs through each character of the string doing the replace) but it should work, and you can change as needed. Good luck
private void textBox1_TextChanged(object sender, EventArgs e)
{
string A = textBox1.Text.Trim();
string[] Aarry = A.Split('|');
string cleanedString = "";
for (int i = 0; i < Aarry.Length; i++)
{
if (i % 2 == 0)
cleanedString += FixText(Aarry[i]) + " ";
else
cleanedString += Aarry[i] + " ";
}
textBox2.Text = cleanedString ;
The method below will go through each character doing the replace
public string FixText(string A)
{
string newText = "";
for (int i = 0; i < A.Length; i++)
{
switch (A.Substring(i, 1))
{
case "A":
newText += A.Substring(i, 1).Replace("A", "C");
break;
case "F":
newText += A.Substring(i, 1).Replace("F", "H");
break;
case "C":
newText += A.Substring(i, 1).Replace("C", "W");
break;
case "B":
newText += A.Substring(i, 1).Replace("B", "G");
break;
default:
break;
}
}
return newText;
}
To handle the >500 lines of replacement type you have, you could setup a dictionary using method below:
public Dictionary<string, string> ReturnReplacementDictionary()
{
Dictionary<string, string> dictLibrary = new Dictionary<string,string)()
{
{"A","C"},
{"F","H"},
{"C","W"},
{"B","G"}
};
return dictLibrary;
}
In the above you would just continue adding in all your other replacement values.
Then you would call use that method below instead of the switch case(If you don't add a character/replacement to the dictionary method you can see it will just set the replacement character to blank):
public string FixTextUsingDictionary(string A)
{
Dictionary<string, string> replaceDict = ReturnReplacementDictionary();
string newText = "";
for (int i = 0; i < A.Length; i++)
{
string replacementLetter="";
if (replaceDict.TryGetValue(A.Substring(i, 1), out replacementLetter))
{
newText += replacementLetter;
}
// Added so that if the char is not in the dictionary the output will just have the original char
else { newText += A.Substring(i, 1); }
}
return newText;
}
Good luck
If the text is entered manually not pasted from clipboard, my solution will be:
int counter = 0;
private string replaceSpecial(string A)
{
if (A.Equals("A")) return "C";
else if (A.Equals("F")) return "H";
else if (A.Equals("C")) return "W";
else if (A.Equals("B")) return "G";
else if (A.Equals("|")) return "";
else return A;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar.Equals('|'))
{
counter++;
}
if (counter == 0 || counter % 2 == 0)
textBox2.Text += replaceSpecial(e.KeyChar.ToString());
else
textBox2.Text += e.KeyChar.ToString().Replace("|", "");
}
considering that the only entered character is "|".
good luck
void StringReplace(string initialString)
{
bool insideSpecialCharacter = false;
string[] Pattern = { "A-C", "C-W", "F-H", "B-G" };
string specialCharacter = "|";
char[] characters = initialString.ToCharArray();
char?[] Newcharacters = new char?[characters.Length];
for (int i = 0; i < characters.Length; i++)
{
if (!characters[i].ToString().Equals(specialCharacter))
{
if (insideSpecialCharacter)
{
Newcharacters[i] = characters[i];
}
else
{
CheckPattern(Pattern, characters, Newcharacters, i);
}
}
else
{
insideSpecialCharacter = (insideSpecialCharacter) ? false : true;
}
}
txtSecond.Text = string.Concat(Newcharacters).Trim();
}
//-------Checks the Pattern Array and Replaces the Characters-----------
private static void CheckPattern(string[] Pattern, char[] characters, char?[] Newcharacters, int i)
{
for (int j = 0; j < Pattern.Length; j++)
{
string[] replaceValue = Pattern[j].Split('-');
if (characters[i].ToString() == replaceValue[0])
{
Newcharacters[i] = Convert.ToChar(characters[i].ToString().Replace(characters[i].ToString(), replaceValue[1]));
break;
}
else
{
Newcharacters[i] = characters[i];
}
}
}
i'm trying to send one parameter from funtion to one any control on the page but i can not do that. what i'm doing wrong?
i checked that the paramter (PDX) is getting right values and they are changing but nothing shown on the any control on the page. (like textbox, listbox etc. i tried all )
private void OnPDXDataArrived(string PDX, bool Header)
{
TextBox1.Text += PDX;
PDXDataArrived(PDX, Header);
}
public string blabla;
private void PDXDataArrived(string PDX, bool Header)
{
int FieldCount = int.Parse(txtUpload_Fields.Text);
int nCnt = 0;
if (Header == true)
{
ListBox4.Items.Add(PDX);
TextBox1.Text += PDX;
blabla += PDX.ToString();
TextBox1.Text = blabla;
Console.WriteLine(blabla);
}
else
{
strTemplete += PDX + "\r";
string nStemp = strTemplete.Substring(0, strTemplete.Length - 1);
datammm = nStemp.Split(new string[] { "\r" }, StringSplitOptions.None);
for (int dx = 0; dx < datammm.Length; dx++) ListBox4.Items.Add(datammm[dx]);
}
}