How to search and replace words in a WPF TextBox? - c#

I've found several examples that do this but with richTextBox instead. Is it even possible to replace words in a multi-line TextBox?

you can do this for searchin' the next word automatically in textbox
int t = 0;
private void FindNext(object sender, RoutedEventArgs e)
{
for (int i = t; i < NoteText.Text.Length-SearchBar.Text.Length; i++)
{
string x = "";
for (int j = 0; j < SearchBar.Text.Length; j++)
{
if(SearchBar.Text[j] == NoteText.Text[i+j])
{
x += NoteText.Text[i + j] + "";
}
else
{
x = "";
}
}
if(x == SearchBar.Text)
{
t = i+1;
NoteText.Focus();
NoteText.SelectAll();
NoteText.Select(i, SearchBar.Text.Length);
break;
}
if(i==NoteText.Text.Length - SearchBar.Text.Length - 1)
{
MessageBox.Show("The search was completed");
t = 0;
}
s = t;
}
}

Related

Merge rows in datagridview

I am trying to make a billing software and want to merge the rows with same barcode with a press of a button, and if that row contains remark then the row should not merge.
private void button3_Click(object sender, EventArgs e)
{
int GROW = dataGridView1.RowCount;
for(int i=0; i<GROW; i++)
{
DataGridViewRow row= dataGridView1.Rows[i];
string A = row.Cells[0].Value.ToString();
for(int j = 0; j< GROW; j++)
{
if(j == i)
{
}
else
{
DataGridViewRow rowb= dataGridView1.Rows[j];
string B = rowb.Cells[0].Value.ToString();
if (A == B)
{
string rema = row.Cells[8].Value.ToString();
string remb = rowb.Cells[8].Value.ToString();
if(rema == "" && remb == "")
{
string qa = row.Cells[2].Value.ToString();
string qb = rowb.Cells[2].Value.ToString();
decimal qad = Convert.ToDecimal(qa);
decimal qbd = Convert.ToDecimal(qb);
decimal tqd = qad + qbd;
string ra = row.Cells[7].Value.ToString();
string rb = rowb.Cells[7].Value.ToString();
decimal rad = Convert.ToDecimal(ra);
decimal rbd = Convert.ToDecimal(rb);
decimal trd = rad + rbd;
row.Cells[7].Value = trd;
row.Cells[2].Value= tqd;
dataGridView1.Rows.RemoveAt(j);
// i = i - 1;
GROW--;
}
}
}
}
}
Assuming your value is in Cell[2] and remark in Cell[8], something like this should work:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int k = 0;
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
// Check if values are same but remarks are different
if (dataGridView1.Rows[i].Cells[2].Value == dataGridView1.Rows[j].Cells[2].Value && dataGridView1.Rows[i].Cells[8].Value != dataGridView1.Rows[j].Cells[8].Value)
{
if (k != 0)
{
items.Rows.RemoveAt(j);
dataGridView1.DataSource = items;
}
k++;
}
}
}
NOTE: I have not tested this code but I hope you get the idea

C# Calculator "Input string was not in a correct format" on every operation except addition

I tried to create a small calculator and everything worked just fine. I could do every operation without an error. Then I tried to improve some things and add some.
Out of a sudden the original Part does not work anymore and i get the Error:[ System.FormatException: "Input string was not in a correct format." ] every time i try to substract, multiply or divide.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator_V2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
answer.Text = Calculate(textBox.Text);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
public string Calculate(string text)
{
double finalAnswer = AddAndSubstract(text);
return finalAnswer.ToString();
}
public double AddAndSubstract(string text1)
{
string[] text = text1.Split('-');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('+') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('+');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "+");
}
}
}
}
double total;
if (textList[0].Contains("*") || textList[0].Contains("/"))
{
total = DivideAndMultiply(textList[0]);
return total;
}
else
{
total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "-")
{
total = total - DivideAndMultiply(textList[i]);
}
else if (textList[i - 1] == "+")
{
total = total + DivideAndMultiply(textList[i]);
}
}
return total;
}
}
public double DivideAndMultiply(string text1)
{
string[] text = text1.Split('*');
List<string> textList = new List<string>();
for (int i = 0; i < text.Length; i++)
{
textList.Add(text[i]);
if (i != text.Length - 1)
{
textList.Add("*");
}
textList.Add("*");
}
for (int i = 0; i < textList.Count; i++)
{
if (textList[i].Contains('/') && textList[i].Length > 1)
{
string[] testPart = textList[i].Split('/');
textList.RemoveAt(i);
for (int j = testPart.Length - 1; j >= 0; j--)
{
textList.Insert(i, testPart[j]);
if (j != 0)
{
textList.Insert(i, "/");
}
}
}
}
double total = Convert.ToDouble(textList[0]);
for (int i = 2; i < textList.Count; i += 2)
{
if (textList[i - 1] == "/")
{
total = total / Convert.ToDouble(textList[i]);
}
else if (textList[i - 1] == "*")
{
total = total * Convert.ToDouble(textList[i]);
}
}
return total;
}
private void Button_Click_C(object sender, RoutedEventArgs e)
{
double finalAnswer = 0;
answer.Text = "";
textBox.Text = "";
}
private void Button_Click_zahl(object sender, RoutedEventArgs e)
{
string s_button = sender.ToString();
textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
}
private void Button_Click_equals(object sender, RoutedEventArgs e)
{
answer.Text = RemoveBrackets(textBox.Text);
}
public string RemoveBrackets(string text)
{
while (text.Contains('(') && text.Contains(')'))
{
int openIndex = 0;
int closeIndex = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '(')
{
openIndex = i;
}
if (text[i] == ')')
{
closeIndex = i;
text = text.Remove(openIndex,closeIndex-openIndex +1).Insert(openIndex,ResolveBrackets(openIndex, closeIndex, text));
break;
}
}
}
for (int i = 1; i < text.Length; i++)
{
if (text[i] == '-' && (text[i]-1=='*' || text[i] - 1 == '/'))
{
for (int j=i-1; j>=0; j++)
{
if (text[j] == '+')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '-';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
else if (text[j] == '-')
{
StringBuilder text1 = new StringBuilder(text);
text1[j] = '+';
text = text1.ToString();
text = text.Remove(i, 1);
break;
}
}
}
}
if (text[0] == '-') //für Fehler wenn - als erste Ziffer
{
text = '0' + text;
}
return Calculate(text);
}
public string ResolveBrackets(int openIndex, int closeIndex, string text)
{
string bracketAnswer = Calculate(text.Substring(openIndex +1, closeIndex -1));
return bracketAnswer;
}
}
}
Because you probably add the minus character twice
if (i != text.Length - 1)
{
textList.Add("-");
}
textList.Add("-");
Then, when you loop in step of 2
for (int i = 2; i < textList.Count; i += 2)
You don't have [number] [sign] [number] [sign] anymore.
I suggest you look and the items in your list to see the problem. I would also suggest that you split your logic into smaller methods that could individually be tested.
i think the problem is your use of
double total = Convert.ToDouble(textList[0]);
in DivideAndMultiply
First of all it's best practice to test if the string is null or empty using String.IsNullOrEmpty(textList[0]); and use Double.TryParse instead of convert.

Skip text in RichTextBox

I would skip the text in the field, if there is no text, but if this is to add text to the beginning and the end. I'm trying like this but it add text every line.
private void zmien(string a, string b)
{
{
if (richTextBox1.Text.Length > 0)
{
string[] lines = richTextBox1.Lines;
for (int i = 0; i < lines.Length; i++)
{
if (richTextBox1.Text.Length == 0)
{
for (int j = 0; i < lines.Length; i++)
lines[i] = Environment.NewLine;
}
else
lines[i] = a + lines[i] + b;
}
richTextBox1.Lines = lines;
//richTextBox1.SelectedText = "test" + lines;
}
}
}
You can do that much simply as you think, try follow this code
private void zmien(string a, string b)
{
if (richTextBox1.Text.Length > 0)
{
richTextBox1.Text = a+" "+richTextBox1.Text+" "+b;
}
}

CheckedListBox.SelectedItems.Count = 1?

In C#, I have checked list boxes, that I need to store the data in arrays, but when I start the event that writes the objects to the array, I have to set the size of the array, which I naturally set to the amount of items checked. However, the items checked, for both checked list boxes I have is 1, no matter how many I check. Can someone help?
public partial class Form3 : Form
{
public static object[] dtype;
public static bool loaded = false;
bool typeselecte = false;
bool typeselectd = false;
public Form3()
{
InitializeComponent();
}
private void Form3_Shown(object sender, EventArgs e)
{
if (loaded)
{
int counte = 0;
int countd = 0;
types1.Items.AddRange(dtype);
types2.Items.AddRange(dtype);
if (typeselecte)
{
for (int i = 0; i < types1.Items.Count; i++)
{
if (i == Form1.enumber[counte])
{
types1.SelectedItems[i] = Form1.esearch[i];
counte++;
}
}
}
if (typeselectd)
{
for (int j = 0; j < types2.Items.Count; j++)
{
if (j == Form1.dnumber[countd])
{
types2.SelectedItems[j] = Form1.dsearch[j];
countd++;
}
}
}
}
}
public void dtypes()
{
dtype = new object[types1.Items.Count];
for (int i = 0; i < types1.Items.Count; i++)
{
dtype[i] = types1.Items[i];
}
}
private void button1_Click(object sender, EventArgs e)
{
if (types1.SelectedItems.Count > 0)
typeselecte = true;
if (types2.SelectedItems.Count > 0)
typeselectd = true;
Form1.esearch = new object[types1.SelectedItems.Count];
Form1.dsearch = new object[types2.SelectedItems.Count];
Form1.enumber = new int[types1.SelectedItems.Count];
Form1.dnumber = new int[types2.SelectedItems.Count];
int counte = 0;
int countd = 0;
if (typeselecte)
{
for (int i = 0; i < types1.SelectedItems.Count; i++)
Form1.esearch[i] = types1.SelectedItems[i];
}
if (typeselectd)
{
for (int j = 0; j < types2.SelectedItems.Count; j++)
Form1.dsearch[j] = types2.SelectedItems[j];
}
if (typeselecte)
{
for (int k = 0; k < types1.Items.Count; k++)
{
if (Form1.esearch[k] == types1.Items[k])
{
Form1.enumber[counte] = k;
counte++;
}
else
{
k--;
}
}
}
if (typeselectd)
{
for (int l = 0; l < types2.Items.Count; l++)
{
if (Form1.dsearch[l] == types2.Items[l])
{
Form1.dnumber[countd] = l;
countd++;
}
else
{
l--;
}
}
}
this.Close();
}
}
Form1.esearch and dsearch are object arrays, which the size hasn't been picked yet, and e and dnumber are int arrays that have unknown size as well, I just didn't feel the need to put in that code.
I believe you need to use the property CheckedItems as opposed to SelectedItems.

Highlighting wrong Spelling in web browser control

What I am trying to do is mark a dotted red Underline to each wrong spelling present in the web browser control which i have used in my winform Application.
Here is my Code snippet :-
public static string CheckSpelling(string InnerHTML)
{
string Val = "";
try
{
StringBuilder strBu = new StringBuilder();
strBu.Append(InnerHTML);
RemoveStyleAssigned(ref strBu);
for (int i = 0; i < strBu.Length; i++)
{
if (Convert.ToString(strBu[i]).ToLower() == "<")
{
for (int j = i + 1; j < strBu.Length; j++)
{
if (Convert.ToString(strBu[j]).ToLower() == ">")
{
i = j;
for (int k = j + 1; k < strBu.Length; k++)
{
if (Convert.ToString(strBu[k]).ToLower() != " ")
{
i = k;
CheckAndReplace(ref strBu, ref i);
break;
}
}
break;
}
}
}
else if (Convert.ToString(strBu[i]).ToLower() != " ")
{
CheckAndReplace(ref strBu, ref i);
}
}
Val = strBu.ToString();
}
catch (Exception ex)
{
}
return Val;
}
Here InnerHTML is the InnerHTML of the web browser control obtained for entered data.
The Next Method is CheckandReplace
private static void CheckAndReplace(ref StringBuilder strBu, ref int i)
{
try
{
string Target = string.Empty;
string NewString = "";
for (int j = i; j <= strBu.Length; j++)
{
if (j == strBu.Length || Convert.ToString(strBu[j]).ToLower() == " " || Convert.ToString(strBu[j]).ToLower() == "<" )
{
string Wordtocheck = ReplaceXmlCharacters(Target);
if (!IsSpellingCorrect(Wordtocheck))
{
NewString = "<u style='text-decoration: none; border-bottom: 1px dotted #FF0000'>" + Target + "</u>";
strBu = strBu.Replace(Target, NewString, i, Target.Length);
i += NewString.Length - 1;
}
else
{
i = j - 1;
}
break;
}
else
Target += strBu[j];
}
}
catch (Exception ex)
{
}
}
The Main Problem is that Everything works fine with the above code but whenever i get any special character or any space in the Target Value, the above code also highlight the same but I don't want to highlight that as done in MS Word. Please Guide me through this or is their any other way out.
Thanks in advance
You may want to check out Regex. Seems like it would help with what you are trying to accomplish.

Categories