I generate textboxes like so:
for (byte i = 0; i < 4; ++i)
for (byte j = 0; j < 4; ++j)
Letterbox[i, j] = new TextBox();
Letterbox[i, j].Style = style; //MaxLength=1 among other things
...
and I'd wish that pasting string like this:
T
Ę
Ś
T
would result in first 4 textboxes containing 'T', 'Ę', 'Ś' and 'T' consecutively.
How can I achieve this?
Clarification (edit):
I want to be able to paste any string in this format (letter, enter, letter, enter...) when the application is running, not hardcode it
Here's an image explaining what I want.
You can use AddPasteHandler
like so:
DataObject.AddPastingHandler(tb, OnPaste);
OnPaste method implementation:
private void OnPaste(object sender, DataObjectPastingEventArgs e)
{
var isText = e.SourceDataObject.GetDataPresent(DataFormats.UnicodeText, true);
if (!isText) return;
var text = e.SourceDataObject.GetData(DataFormats.UnicodeText) as string;
HandlePaste(text);
e.Handled = true;
}
private void HandlePaste(string text)
{
var letters = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (letters.Length == 4)
{
for (var i = 0; i < 4; i++)
{
Letterbox[0, i].Text = letters[i];
}
}
}
tb is some other TextBox on my window, you can use whatever suits your requirements.
In HandlePaste pasted string is split by newlines and when it fits into 4 textboxes Text of each of them is set to appropriate letter. You could add some more validation here like checking if each of strings is exactly one char in length.
Related
I have attached in my listbox ( lb1 ) a character to the previous item. The letter A is seperated by a comma. Is it even possible to replace the letter in this line
(A --> B)? How can this be solved? The result in the listbox( lb2 ) should look as shown below.
if (listBox1.Items.Cast<string>().Contains("someText"))
{
int a = listBox1.Items.IndexOf("someText");
listBox1.Items.RemoveAt(a);
listBox1.Items.Insert(a, "newText");
}
Here is a code snippet for your new problem mikee:
You need to iterate through the items of the list box, search for a match, and replace the detected matches:
string search = "A";
string replace = "B";
for(int i = 0; i < lb1.Items.Count; i++)
{
if(lb1.Items[i].ToString().EndsWith(search))
{
string item = lb1.Items[i].ToString().Replace(search, replace);
lb1.Items[i] = item;
}
}
Edit
Please note that, the preceding snippet will change all the A characters in the string with B not only the last one. So if you have a list item say JONATHAN, A, the preceding code will change it to JONBTHBN, B. To avoid that you could do:
Solution 1:
for (int i = 0; i < lb1.Items.Count; i++)
{
if (lb1.Items[i].ToString().EndsWith(search))
{
int indx = lb1.Items[i].ToString().LastIndexOf(search);
string item = lb1.Items[i].ToString().Substring(0, indx) + replace;
lb1.Items[i] = item;
}
}
Solution 2:
If all of your list items are comma separated strings like the image above, then you could do:
for (int i = 0; i < lb1.Items.Count; i++)
{
if (lb1.Items[i].ToString().EndsWith(search))
{
var arr = lb1.Items[i].ToString().Split(',');
arr[arr.Length - 1] = replace;
lb1.Items[i] = string.Join(", ", arr);
}
}
Sorry for any inconvenience mikee.
Good luck.
I want to include two text box texts to one text box like this
both of them are multiline.
But I want special form of include, in other words I want to include them like this
textbox 1 texts: '' help''' '' other''
textbox 2 texts:' 1' '2' '' 3''
results: help1 _ help2 _ help3
other1_other2_other3
Multiline textboxes return a string array with the lines in the Lines property. You could do something like this
string[] words = textBox1.Lines;
string[] numbers = textBox2.Lines;
var resultLines = new string[words.Length];
var sb = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
sb.Length = 0; // Reset StringBuilder for the next line.
for (int j = 0; j < numbers.Length; j++) {
sb.Append(words[i]).Append("-").Append(numbers[j]).Append("_");
}
if (sb.Length > 0) {
sb.Length--; // remove the last "_"
}
resultLines[i] = sb.ToString();
}
resultsTextBox.Lines = resultLines;
First we get the words and numbers arrays. Then we create a new array for the result. Since we want a result line for each word, we make it words.Length in size.
Then we loop through the words. We use a StringBuilder to build our new lines. This is more efficient as concatenation strings with +, as it minimizes copy operations and memory allocations.
In a nested loop we put the words and numbers together.
An elegant way to solve your issue is to make use of the String.Join method in C#. I'm adding this answer because I'm a big fan of the method and think it must be part of some answer to this question because it has to do with combining strings.
Here's the code that I'd use to solve the challenge:
string[] firstInput = textBox1.Lines;
string[] secondInput = textBox2.Lines;
var combinedInputs = new string[firstInput.Length];
var combinedLine = new string[secondInput.Length];
for(int i = 0; i < firstInput.Length; i++)
{
for(int j = 0; j < secondInput.Length; j++)
{
combinedLine[j] = firstInput[i] + secondInput[j];
}
//Combine all values of combinedLine with a '-' in between and add this to combinedInputs.
combinedInputs[i] = String.Join("-", combinedLine);
}
outputTextBox.Lines = combinedInputs; //the resulting output
I hope this answer helped aswell. And I'd like to give credits to Olivier for explaining the textbox part. Another thing that I'd like to add is that this answer isn't meant to be the most efficient, but is meant to be easy to read and understand.
Okay so I'm making an auto typer and I want the user to be able to enter the keys {}()^+ and have the application out put. I know that you need to format the symbols like SendKeys.Send({^}); but I cant get this to work. Heres what I have so far for my Timer Tick. Also, I have global int blockCount, which tells the program to move on to the next character in the blockText string.
It returns "Group delimiters are not balanced."
private void timer3_Tick(object sender, EventArgs e)
{
string blockText = richTextBox1.Text;
int blockLength = richTextBox1.TextLength;
btrand = RandomNumber(75, 200); //I have a method to make a rand num
timer3.Interval = btrand;
char[] specialChars = { '{', '}', '(', ')', '+','^' };
foreach (char letter in blockText)
{
for (int i = 0; i < specialChars.Length; i++)
{
if (letter == specialChars[i])
{
SendKeys.Send("{" + specialChars[i] + "}");
blockText.Remove(blockText.IndexOf(specialChars[i].ToString()));
}
else
{
SendKeys.Send(letter.ToString());
}
}
}
blockCount++;
if (blockCount >= blockLength)
{
blockCount = 0;
}
}
Ok, quick analysis, so forgive me if I miss something.
You're doing a foreach using blockText as your collection, and manipulating it if a special char is found. This can be messy; I would think on another way to implement this.
You're looping through all special chars, and for each interaction that you can't identify a match you're sending the current letter. That means you're re-sending all non-special characters for the number of elements in the specialChars array minus one. I don't think that's what you've intended to do.
I would suggest an implementation like this:
foreach (char letter in blockText)
{
bool _specialCharFound = false;
for (int i = 0; i < specialChars.Length; i++)
{
if (letter == specialChars[i])
{
_specialCharFound = true;
break;
}
}
if (_specialCharFound)
SendKeys.Send("{" + letter.ToString() + "}");
else
SendKeys.Send(letter.ToString());
}
There are more optimized ways to implement, but I would choose this one out of clarity of purpose and similarity to your original code.
I have a problem with C#.
I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again.
Now I don't know how to navigate through the file (forward and backward) to the line I want.
Can anybody help?
You can do something like this:
var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
//Find the word the first time
if(!foundFirstTime && text[i].Contains("word"))
{
//Skip 3 lines - and continue
i = Math.Min(i+3, text.Length-1);
foundFirstTime = true;
}
if(foundFirstTime && text[i].Contains("word"))
{
//Do whatever!
}
}
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
select lines).ToList<string>();
for (int i = 0; i < query.Count; i++)
{
if (query[i].Contains("TextYouWant"))
{
i = i + 3;
}
}
Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:
string[] lines = System.IO.File.ReadAllLines("File.txt");
int skip = 3;
string word = "foo";
string pattern = string.Format("\\b{0}\\b", word);
for (int i = 0; i < lines.Count(); i++)
{
var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);
System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));
if (match) i += skip;
}
If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.
I have a simple program it has a function to read a line from multiline textBox when i press a button
what i made to do that is this code :
TextReader read = new System.IO.StringReader(textBox1.Text);
int rows = 100;
string[] text1 = new string[rows];
for (int r = 1; r < rows; r++)
{
text1[r] = read.ReadLine();
}
so when click button1 it the code will be like this:
textBox2=text1[1];
[1] mean the first line How can i do it automaticaly by one click ?
or with one click the first line to textBox2
the second to textBox3 .....ect..
plz i want the code and where i should put it ^_^
or if there is another way to do that
The property Lines is there for you
if(textBox1.Lines.Length > 0)
textBox2.Text=textBox1.Lines[0];
or, put your textboxes ordered in a temporary array and loop on them (of course we should always check the number of lines present in textBox1)
TextBox[] text = new TextBox[] {textBox2, textBox3, textBox4};
if(textBox.Lines.Length >= 3)
{
for(int x = 0; x < 3; x++)
text[x] = textBox1.Lines[x];
}
Simple programming read and write a one-by-one line from multiline textBox in C#
Write line one-by-one:
textbox1.AppendText("11111111+");
textbox1.AppendText("\r\n222222222");
textbox1.AppendText("\r\n333333333");
textbox1.AppendText("\r\n444444444");
textbox1.AppendText("\r\n555555555");
Read line one-by-one:
for (int i = 0; i < textbox1.Lines.Length; i++)
{
textbox2.Text += textbox1.Lines[i] + "\r\n";
}
You can use following snippet for reading comma separated and newline separated values from multiline textbox -
if (!string.IsNullOrEmpty(Convert.ToString(txtBoxId.Text)))
{
string IdOrder = Convert.ToString(txtBoxId.Text.Trim());
//replacing "enter" i.e. "\n" by ","
string temp = IdOrder.Replace("\r\n", ",");
string[] ArrIdOrders = Regex.Split(temp, ",");
for (int i = 0; i < ArrIdOrders.Length; i++)
{
//your code
}
}
I Hope this would help you.