Using user input numbers to find a word in a textbox - c#

Currently trying to work out how I use user inputs. In my case it is 1/2/3 to find a specific line and word in a text box and copy that information and output the word into a new text box. The text box the user inputs into has already been split so the first number chooses the text file to choose a word from the second number chooses a line and the third number chooses a word. After the first number is read the chosen text file is going to be output into a rich text box before the keyword is discovered and output.
So far I don't have much code towards this but the only part I really don't understand is how to find the specific line and word. Currently the text box with the three user inputs is being broken up into each individual section and being stored in invisible labels for each section as you can see in my code.
Here's my code so far:
public partial class Form1 : Form
{
int NumLines;
public Form1()
{
InitializeComponent();
}
private void btnSubmit1_Click(object sender, EventArgs e)
{
var charArray = txtPoemInput.Text.Split('/'); // Dividing the users input into 3 usable sections using invisible labels
lblPoem.Text = charArray[0];
lblLine.Text = charArray[1];
lblWord.Text = charArray[2];
// Testing for which poem is going to be used
if (lblPoem.Text == "1")
{
//Read in text file
}
else if (lblPoem.Text == "2")
{
//Read in text file
}
else if (lblPoem.Text == "3")
{
//Read in text file
}
NumLines = txtPoem.Lines.Count();
// the user input line and word finds and selects the speciic word required
// Displays word in the Keyword box

Related

How to change text field in a PPT programmatically in C#?

I have a PPT template in which I need to programmatically replace some text fields with data that comes from my database then convert the ppt to pdf and send it as attachment in an email. I am not sure of how to change the content of text fields in the PowerPoint Presentation. I think OpenXML needs to be used.
Please help me to feed dynamic data into my ppt template.
I have worked previously with the DocumentFormat.OpenXml from Microsoft but with word files. I played a bit with it to replace some Texts in a Power Point file.
Here is my simple test code snippet:
static void Main(string[] args)
{
// just gets me the current location of the assembly to get a full path
string fileName = GetFilePath("Resource\\Template.pptx");
// open the presentation in edit mode -> the bool parameter stands for 'isEditable'
using (PresentationDocument document = PresentationDocument.Open(fileName, true))
{
// going through the slides of the presentation
foreach (SlidePart slidePart in document.PresentationPart.SlideParts)
{
// searching for a text with the placeholder i want to replace
DocumentFormat.OpenXml.Drawing.Text text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[TITLE]]");
// change the text
if (text != null)
text.Text = "My new cool title";
// searching for the second text with the placeholder i want to replace
text =
slidePart.RootElement.Descendants<DocumentFormat.OpenXml.Drawing.Text>().FirstOrDefault(x => x.Text == "[[SUBTITLE]]");
// change the text
if (text != null)
text.Text = "My new cool sub-title";
}
document.Save();
}
}
In my case i had a simple presentation with one slide and in the Text fields the entries "[[TITLE]]" and "[[SUBTITLE]]" which i replaced with this text.
For my test file this worked well but maybe you will need to adopt / change something for your specific file.
E.g. in Word i had sometimes texts which was splitted in multiple Text parts within a Run element and had to write a logic to "collect" this data and replace them with one Text element with the new text i wanted to be there or maybe you have to search for other Descendant types.

Variable IDs in C#

When programming a Windows Forms application I found myself having to create a variable amount of text fields according to the number of inputs.
I decided to name these name1, name2, name3, ..., nameN.
Now I want to be able to save the user's input to a text file. To do this I need to get the text from the text boxes into separate variables to be able to write this to the text file.
This would result in a for loop like this:
for(i=0; i < totalnames; i++)
{
string varname= "name" + i;
}
But this way I cannot get the value from the text boxes. How can I get the separate values from the text boxes to write them to the text file?
Thank you,
When you create the form controls, keep references to them in a list:
// probably at the class level...
List<TextBox> myTextBoxes = new List<TextBox>();
// then when you create them...
myTextBoxes.Add(name1);
// etc.
Then later, when you need to reference them, use the list:
foreach (var textBox in myTextBoxes)
{
// get the value from the text box and use it in your output
}
You can create a List of string List and add your name in it. Then use StreamWriter to add the name in your file:
List<string> myListOfNames = new List<string>();
int totalnames = 10;
for (int i = 0; i < totalnames; i++)
{
myListOfNames.Add("name" + i);
}
using (StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", true))
{
foreach (string name in myListOfNames)
{
writer.WriteLine(name);
}
}
Here is my two pennies worth, because the OP originally said Windows Form Application - I would have a Save button, which when fired, the code behind will grab all the Textboxes and save to the file. You can add your own filtering for textboxes yourself if you want.
Firstly here is the code behind for the button event:
private void saveToFile_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter("C:\\k\\saveToFile.txt", true))
{
if (this.Controls.Count > 0)
{
var textBoxes = this.Controls.OfType<TextBox>();
foreach (TextBox textbox in textBoxes)
{
writer.WriteLine(textbox.Name + "=" + textbox.Text);
}
}
}
}
A simple forn to prove the point, each TextBox has a name of name1 etc.
Also here is an example output of the file:
Improvements
Filtering on the Textboxes - you may only want to do this for some textboxes for a particular name.
Loading the file. I have added the textbox name to the file, so theorically you could load the data back into the textboxes.

How to access the Text of the ClassName RichTextBox

I'm attempting to find a document on my window that has a rich text box with text in it using TestStack White, and extract that text.
I've tried to use the UIItem Label & TextBox, but White doesn't seem to be able to find the object during my test. The object can be found using the generic UIItem, but I want to be able to access the text it holds.
I'm implementing it like:
public [Unsure] MyRichTextBox
{
get { return Window.Get<[Unsure]>(SearchCriteria.ByClassName("RichTextBox")); }
}
and I'd like to be able to say:
Assert.That(MyRichTextBox.Text.Equals(x));
But it can't find what I'm looking for if I tag it as a Label or a TextBox, and I don't have access to .Text if I declare it a UIItem.
You want to use the type of TextBox. Then you can use BulkText to access the text in the RichEditBox.
First the Window:
TestStack.White.UIItems.WindowItems.Window _mainWindow;
app = TestStack.White.Application.Launch(startInfo);
_mainWindow = app.GetWindow("MyDialog");
Then Find the richEditBox:
public string _richeditdocument_ID = "rtbDocument";
private TextBox _richeditdocument_ = null;
public TextBox RichEditDocument
{
get
{
if (null == _richeditdocument_)
_richeditdocument_ = _mainWindow.Get<TextBox>(SearchCriteria.ByAutomationId(_richeditdocument_ID));
return _richeditdocument_;
}
}
Then use the following to access the text:
string data = RichEditDocument.BulkText;
Here are the code comments for using the Text Method in White:
// Summary:
// Enters the text in the textbox. The text would be cleared first. This is
// not as good performing as the BulkText method. This does raise all keyboard
// events - that means that your string will consist of letters that match the
// letters of your string but in current input language.
public virtual string Text { get; set; }
Here are the comments for using BulkText:
// Summary:
// Sets the text in the textbox. The text would be cleared first. This is a
// better performing than the Text method. This doesn't raise all keyboard events.
// The string will be set exactly as it is in your code.

Finding & Replacing text in a MS Word textbox

I am trying to replace the temporary text in a word document with new text from a list. It works if the text is not in a shape, but once it tries to find the text in a textbox it throws an error. Here is what I have so far:
public void FindReplace(List<repvals> replaceVals, string docLocation, int listLen)
{
//Opens a new Word application
var app = new Microsoft.Office.Interop.Word.Application();
//Opens the .docx
var doc = app.Documents.Open(docLocation, true, false);
//Selects the document
var range = doc.Range();
for (int i = 0; i < listLen; i++)
{
//Finds the parameter, then replaces
range.Find.Execute(FindText: Convert.ToString(replaceVals[i].tempVal), Replace: WdReplace.wdReplaceAll, ReplaceWith: Convert.ToString(replaceVals[i].Boxes));
var shapes = doc.Shapes;
//Finds text within textboxes, then changes them
foreach (Microsoft.Office.Interop.Word.Shape shape in shapes)
{
var initialText = shape.TextFrame.TextRange.Text;
var resultingText = initialText.Replace(Convert.ToString(replaceVals[i].tempVal), Convert.ToString(replaceVals[i].Boxes));
shape.TextFrame.TextRange.Text = resultingText;
}
}
//prints document
doc.Save();
doc.Close();
//fully closes Word
Marshal.ReleaseComObject(app);
}
The problem occurs when it hits
var initialText = shape.TextFrame.TextRange.Text;
And throws an error saying: "This object does not support attached text."
The text in the shapes are nothing special. (e.g. tDATE, tNAME, etc.)
Any ideas?
I found the answer. Turns out my code was fine, however the document I was using (which I didn't write), had another shape on the second to last page to form a place to sign your name. I replaced that with an underscore, ran the code, and everything changed perfectly.
For those who also experience this problem, try checking how many shapes your foreach loop has counted:
http://i.imgur.com/1yNrL4p.png
Thank you Andrew and varocarbas for the help
*"In 2003 the AltText default for a standard textbox WAS the contained text BUT since you can change the Alt Text to NOT match it was never a good idea to read it this way. In 2010 the default for Alt Text is blank
If the textbox is named "Text Box 2" (substitute the correct name if not)
MsgBox ActiveDocument.Shapes("Text Box 2").TextFrame.TextRange should work."*
--
John SR Wilson
http://answers.microsoft.com/en-us/office/forum/office_2010-customize/shapesalternativetext-is-blank-for-the-docx/7671c746-2c2b-41d9-b7de-389a766587a7?page=2&msgId=31041d67-e62b-4ce0-b283-57fd6a4ff6b2

C# Text Box File Import

I've got a form with multiple text boxes which are file paths for the program to import data from. Currently they are checked for non-zero length by the following:
//this code imports the files required by the user, as specified in the
//file path text boxes
private void btImport_Click(object sender, EventArgs e)
{
bool hasPath = false;
foreach (TextBox box in this.gbPaths.Controls.OfType<TextBox>().Where(tb => tb.Text.Length > 0))
{
hasPath = true;
//import code
}//end foreach
if (!hasPath)
{
MessageBox.Show("You must enter at least one file path.");
}//end if
}//end import code
What I'm wondering is can I replace the //import code part with something like:
if(tb.Name = "txtAvF") then...
or similar, or do I have to do it outside of the foreach loop? Thanks in advance. Let me know if I need to clarify anything.
If you want to check to see if the TextBox is one of the ones on the form (which I think you are), then you are == which (taken from MSDN)
the operator == tests for reference equality by determining if two references indicate the same object
So this is what you're looking for:
if(box == textBox1 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox1
}
else if(box == textBox2 && !string.IsNullOrEmpty(box.Text))
{
// Import Textbox2
}
else if (box == textBox3....)
You should do it inside of the loop. Like this:
if (box.Name == "txtAvF")
box.Text = "What you want";
But setting hasPath inside the loop just holds state for your last path. You should also move MessageBox code inside loop.
The hasPath assignment seems correct to me; it's set for any one text box, and if not set at the end of the loop, a message is displayed. This rhymes well with the text so displayed. Moving the MessageBox call into the loop would cause the dialog box to never be displayed (or errenously displayed), at least as the code is implemented now, since the OfType<>().Where() guarantees that all text boxes iterated over have at least some content.
(I would add this as a comment to #Xaqron but don't have the necessary reputation yet.)

Categories

Resources