I am using Windows Form Application, in the application, there is two rich Textbox and one Button, I want the RichTextbox 2 to display RichTextbox 1 after using the Dictionary.How to do that?What is the code for the Button?
public Form1()
{
InitializeComponent();
Dictionary<char, string> dictionary = new Dictionary<char, string>();
dictionary.Add('a', "%");
dictionary.Add('A'," %");
dictionary.Add('b', " &");
dictionary.Add('B', " &");
dictionary.Add('c', " <");
dictionary.Add('C', " <");
}
private void button_Click(object sender, EventArgs e)
{
second_richtextbox= (???)
}
So that when I type cab it will translate to "<%&"
I want to translate the letter to different symbol.
Here's one way you could do it, using LINQ:
private void button_Click(object sender, EventArgs e)
{
second_richtextbox.Text = string.Join("",
first_richtextbox.Text
.Select(ch =>
dictionary.ContainsKey(ch) ? dictionary[ch] : ch.ToString()));
}
Or a more straightforward way using a loop and StringBuilder (I'd probably do it this way):
var result = new StringBuilder();
for (int i = 0; i < first_richtextbox.Text.Length; i++)
{
if (dictionary.ContainsKey(text[i]))
{
result.Append(dictionary[text[i]]);
}
else
{
result.Append(text[i]);
}
}
second_richtextbox.Text = result.ToString();
Try this code on your Click Event of Button
string frstvalue = richTextBox1.Text;
string finalvalue = "";
char[] a = richTextBox1.Text.ToArray();
foreach (char c in a)
{
if (dictionary.ContainsKey(c))
{
string value = dictionary[c];
finalvalue += value;
}
}
richTextBox2.Text = finalvalue;
I hope it will help
Related
When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.
I have a very simple form that produces a Datagridview with 4 columns. No problem generating the form. Only the last column can be edited. After editing, I want to hit the OK button and join elements of the list in the last column into a string. How do I make that list (current) available inside the the OK button object sender. Sorry for my poor grammar. I'm an obvious newbie. Thanks.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Avisynth_Script
{
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
public string current_values = null;
private void Load_Tweaker(object sender, EventArgs e)
{
string[] deshake_parts = EntryPoint.deshakeSettings.Split(',');
List<String> settings = new List<string>(deshake_parts);
string[] default_values = EntryPoint.deshakeDefaultValues.Split(',');
List<String> defaults = new List<string>(default_values);
string[] current_settings = current_values.Split('|');
//current_settings[0] = current_settings[0].Substring(1);
//current_settings[66] = current_settings[66].Substring(0, 6);
List<String> current = new List<string>(current_settings);
dataGridView1.Rows.Clear();
for (int i=0; i < settings.Count; i++)
{
dataGridView1.Rows.Add(i+1 ,settings[i], defaults[i], current[i]);
}
}
private void OK_button_Click(object sender, EventArgs e)
{
EntryPoint.deshaker_param = string.Join('|', current.ToArray());
}
}
}
You have an unbound DataGridView with four columns and want to concatenate the values in the fourth column separated by a "|" in the OK_button_Click method.
You could use a foreach loop to iterate each row in the DataGridView's row collection and pull the value from the fourth column (index=3) to achieve this, or you could use a Linq query to perform the iteration.
Here is a Linq solution.
private void OK_button_Click(object sender, EventArgs e)
{
EntryPoint.deshaker_param = string.Join("|", dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => (!row.IsNewRow)).Select(row =>((row.Cells[3].Value ?? string.Empty).ToString())));
}
It wouldn't be too difficult to move current to be a field-level variable, but that isn't the best option. Now that C# has lambdas in the language, you can basically inline the event handler and remove the OK_button_Click method entirely. This kind of encapsulation is a more robust approach than just making your variables have a higher level of access.
Using a field is like saying that someone in particular needs to write to a file on your computer so you'll just make that file available for everyone to access. You wouldn't do that with your files on your computer so you shouldn't do that in your code.
Inside a lambda you can access the method's local variables. You code can look like this:
List<String> current = new List<string>(current_settings);
OK_button.Click += (s, e2) =>
{
EntryPoint.deshaker_param = string.Join("|", current.ToArray());
};
If you only ever call Load_Tweaker once then your code can be very simple:
private void Load_Tweaker(object sender, EventArgs e)
{
string[] deshake_parts = EntryPoint.deshakeSettings.Split(',');
List<String> settings = new List<string>(deshake_parts);
string[] default_values = EntryPoint.deshakeDefaultValues.Split(',');
List<String> defaults = new List<string>(default_values);
string[] current_settings = current_values.Split('|');
//current_settings[0] = current_settings[0].Substring(1);
//current_settings[66] = current_settings[66].Substring(0, 6);
List<String> current = new List<string>(current_settings);
OK_button.Click += (s, e2) =>
{
EntryPoint.deshaker_param = string.Join("|", current.ToArray());
};
dataGridView1.Rows.Clear();
for (int i = 0; i < settings.Count; i++)
{
dataGridView1.Rows.Add(i + 1, settings[i], defaults[i], current[i]);
}
}
However, if you call Load_Tweaker more than once you need to manage the addition and removal of the handler for each call. It's a little more complicated, but not too bad.
private EventHandler okButtonClick = null;
private void Load_Tweaker(object sender, EventArgs e)
{
string[] deshake_parts = EntryPoint.deshakeSettings.Split(',');
List<String> settings = new List<string>(deshake_parts);
string[] default_values = EntryPoint.deshakeDefaultValues.Split(',');
List<String> defaults = new List<string>(default_values);
string[] current_settings = current_values.Split('|');
//current_settings[0] = current_settings[0].Substring(1);
//current_settings[66] = current_settings[66].Substring(0, 6);
List<String> current = new List<string>(current_settings);
if (okButtonClick != null)
{
OK_button.Click -= okButtonClick;
}
okButtonClick = (s, e2) =>
{
EntryPoint.deshaker_param = string.Join("|", current.ToArray());
};
OK_button.Click += okButtonClick;
dataGridView1.Rows.Clear();
for (int i = 0; i < settings.Count; i++)
{
dataGridView1.Rows.Add(i + 1, settings[i], defaults[i], current[i]);
}
}
I have written a code for extracting number from a text file using a windows From. Problem is that, Output Occurs in a partial way. Either the First Line is Printing or the Last Line. I want all the line that is containing the number
(i.e) If the text file contains,
Auto 2017
Mech 2056
CSE 2016
I want only those 2017, 2056, 2016 to be printed.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = Regex.Match(allDetails, #"\d+").Value;
richTextBox1.Text = result.ToString();
}
You are try to grab numeric value. Regex.Matches Will help you to solve your problem.
Below is simplified code.
private void button1_Click(object sender, EventArgs e)
{
string filedetails = File.ReadAllText(textBox1.Text);
var regexCollection = Regex.Matches(filedetails, #"\d+");
foreach (Match rc in regexCollection)
richTextBox1.AppendText(rc.Value + ",");
}
You can do this way, if you want output 2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
string temp = "";
int i = 0;
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
if (i == 0)
{
temp = result;
}
else
{
temp = temp + "," + result;
}
i++;
}
richTextBox1.Text = temp;
}
or if you want single value 2017 2056 2016 then
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
richTextBox1.Text = result ;
}
}
You need to use the method. Regex.Matches. Matches method searches the specified input string for all occurrences of a regular expression.
Match method returns the first match only, Subsequent matches need to be retrieved.
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
var regexMatchCollection = Regex.Matches(allDetails, #"\d+");
foreach(Match mc in regexMatchCollection)
{
richTextBox1.AppendText(mc.Value);
richTextBox1.AppendText(",");
}
}
test.txt has
Auto 2017
Mech 2056
CSE 2016
in the following program File.ReadAllLines will store every line in a string array separately.Then we will use foreach loop to read single line at a time and store the extracted numbers in list e.g 2017 and finally with string.Join we will join the array and separate each word with "," and save it in string
List<string> list = new List<string>();
var textfile = File.ReadAllLines(#"D:\test.txt");
foreach (var line in textfile)
{
string result = Regex.Match(line, #"\d+").Value;
list.Add(result);
}
string numbers = string.Join(",",list.ToArray());
the output value will be
2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = string.Empty;
foreach (var item in Regex.Matches(allDetails, #"\d+"))
{
result = result + item.ToString() + ",";
}
richTextBox1.Text = result.TrimEnd(',');
}
Without using Regex,below is the simplified code
private void button1_Click(object sender, EventArgs e)
{
StringBuilder numbers = new StringBuilder();
string allDetails = File.ReadAllText(textBox1.Text);
foreach(string word in allDetails.Split(' '))
{
int number;
if(int.TryParse(word, out number))
{
numbers.Append(number);
numbers.Append(",");
}
}
richTextBox1.Text = numbers.Trim(',');
}
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\admin\Desktop\ConsoleApplication1\ConsoleApplication1\txtFile.txt");
List<string> Codelst = new List<string>();
foreach (var item in lines)
{
var a= Regex.Match(item, #"\d+").Value;
Codelst .Add(a);
}
var r = Codelst;
}
Output is like this:
I am trying to list all combobox items in one messagebox. but all i get is every item comes up in its own messagebox. I know the messagebox needs to be outside the loop but when i do that it says the variable is unassigned. Any help would be great.
private void displayYachtTypesToolStripMenuItem_Click(object sender, EventArgs e)
{
string yachtTypesString;
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=typeComboBox.Items[indexInteger].ToString();
MessageBox.Show(yachtTypesString);
}
}
Do it like this,
StringBuilder yachtTypesString = new StringBuilder();
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString());
}
MessageBox.Show(yachtTypesString.ToString());
NOTE: Do not do string concatenation with a string, use StringBuilder object as doing it in a string creates a new instance.
You can try using Linq:
MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>()));
and let it do all the work for you
Try this
string yachtTypesString="";
for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++)
{
yachtTypesString=yachtTypesString + typeComboBox.Items[indexInteger].ToString();
}
MessageBox.Show(yachtTypesString);
list all combobox items in one messagebox
Please play with Below code To Get Combobox all Text
private void Form1_Load(object sender, EventArgs e)
{
DataTable dtcheck = new DataTable();
dtcheck.Columns.Add("ID");
dtcheck.Columns.Add("Name");
for (int i = 0; i <= 15; i++)
{
dtcheck.Rows.Add(i, "A" + i);
}
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = dtcheck;
}
}
private void button1_Click(object sender, EventArgs e)
{
string MessageText = string.Empty;
foreach(object item in comboBox1.Items)
{
DataRowView row = item as DataRowView;
MessageText += row["Name"].ToString() + "\n";
}
MessageBox.Show(MessageText, "ListItems", MessageBoxButtons.OK,MessageBoxIcon.Information);
}
Here's my requirement. There is a public website which takes alphanumeric string as input and Retrieves data into a table element (via button click). The table element has couple of labels which gets populated with corresponding data. I need a tool/solution which can check if a particular string exists in the website's database. If so retrieve all the Ids of all the occurrences of that string. Looking at the "view source" of the website (No JavaScript used there), I noted the input element name and the button element name and with the help of existing samples I was able to get a working solution. Below is the code which works but I want to check if there is any better and faster approach. I know the below code has some issues like "infinite loop" issue and others. But I am basically looking at alternate solution which can work quickly for a million records.
namespace SearchWebSite
{
public partial class Form1 : Form
{
bool searched = false;
long i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = null;
if (searched == false)
{
b = (WebBrowser)sender;
b.Document.GetElementById("txtId").InnerText = "M" + i.ToString();
b.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
if (b.ReadyState == WebBrowserReadyState.Complete)
{
if (b.Document.GetElementById("lblName") != null)
{
string IdNo = "M" + i.ToString();
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
{
using (StreamWriter w = File.AppendText("log.txt"))
{
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
else
{
i = i + 1;
searched = false;
}
}
}
}
}
If the page after seach button clicked contains txtId and btnSearch controls than you can use this code snippet, this is not faster but the correct form I think.
public partial class Form1 : Form
{
bool searched = false;
long i = 1;
private string IdNo { get { return "M" + i.ToString(); } }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 1;
WebBrowser browser = new WebBrowser();
string target = "http://www.SomePublicWebsite.com";
browser.Navigate(target);
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(XYZ);
}
private void XYZ(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser b = (WebBrowser)sender;
if (b.ReadyState == WebBrowserReadyState. Complete)
{
if (searched == false)
{
DoSearch(b); return;
}
if (b.Document.GetElementById("lblName") != null)
{
string DateString = b.Document.GetElementById("lblDate").InnerHtml;
string NameString = b.Document.GetElementById("lblName").InnerHtml;
if (NameString != null && (NameString.Contains("XXXX") || NameString.Contains("xxxx")))
using (StreamWriter w = File.AppendText("log.txt"))
w.WriteLine("Id {0}, Date {1}, Name {2}", IdNo, DateString, NameString);
}
i++;
DoSearch(b);
}
}
private void DoSearch(WebBrowser wb)
{
wb.Document.GetElementById("txtId").InnerText = IdNo;
wb.Document.GetElementById("btnSearch").InvokeMember("click");
searched = true;
}
}