This is going to sound really stupid, but I'm taking a class in C# where we are skipping around the book and working only from a console application. We were given an exercise to build sentences in strings based on arrays of articles, nouns, verbs, and prepositions, and capitalize the first letter in the first word of the string. The kicker is, it wants the output to a text box. That wouldn't be a problem except
a) we have bypassed all chapters regarding GUIs (that will come in the next quarter's C# class), and
b) I have checked the book and even Stack Overflow and other online sources, but couldn't figure it out.
Unfortunately, my instructor chose not to discuss this exercise in class last night. Since he and I aren't on the same page (not a dislike, more of a chemistry thing), I'm trying to figure this out on my own. And the deadline for turning this in has passed, so I'm only asking for personal edification at this point.
So, here's the code I created. I wrote it for output to a console just to show I had the basic mechanism of the problem. I know I have to create a separate form with a text box inside a GUI window, but I couldn't figure out how to send the output to a text box rather than a console.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16._4_StoryWriter
{
class StoryWriter
{
static void Main(string[] args)
{
string[] articles = { "the", "a", "one", "some", "any" };
string[] nouns = { "boy", "girl", "dog", "town", "car" };
string[] verbs = { "drove", "jumped", "ran", "walked", "skipped" };
string[] preps = { "to", "from", "over", "under", "on" };
string articleStory = "";
string nounStory = "";
string verbStory = "";
string prepStory = "";
Random random = new Random();
for (int counter = 1; counter <= 10; ++counter)
{
int randomNext = random.Next(5);
articleStory = articles[randomNext];
randomNext = random.Next(5);
nounStory = nouns[randomNext];
randomNext = random.Next(5);
verbStory = verbs[randomNext];
randomNext = random.Next(5);
prepStory = preps[randomNext];
Console.WriteLine(UppercaseFirst(articleStory) + " " + nounStory + " " + verbStory + " " + prepStory + ".");
} // End For
Console.Read();
} // End Main
static string UppercaseFirst(string s) // Borrowed from dotnetperls.com tutorial for making first letter uppercase
{
if (string.IsNullOrEmpty(s)) // Checks for an empty string
{
return string.Empty;
}
char[] a = s.ToCharArray(); // Creates array of characters from a string
a[0] = char.ToUpper(a[0]); // Selects value of zeroth position and changes to upper case
return new string(a); // Passes new string back
} // End method
} // End Class
} // End Namespace
To create a Windows Forms Application project Start Visual Studio
2010.
On the File menu, point to New, and then select Project.
The New Project dialog box appears.
In the Installed Templates pane, expand Visual Basic or Visual C#, and
then select Windows.
Above the middle pane, select the target framework from the drop-down
list.
In the middle pane, select the Windows Forms Application template.
NoteNote The Windows Forms Application template in the .NET Framework
4 targets the Client Profile by default.
In the Name text box, specify a name for the project.
In the Location text box, specify a folder to save the project. Click
OK.
The Windows Forms Designer opens and displays Form1 of the project.
SOURCE
Then drag textbox from toolbox and place it on the form.
Double click anywhere on the form, except for textbox, which will open code behind form and you will be in form load event.
Add:
textBox1.Text = "Your text to put in textbox";
in:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Your text to put in textbox";
}
press F5
Youtube Form
Youtube textbox
You just need a Form and a TextBox as a child of the Form:
var form = new Form{Width = 300, Height = 100, Text = "The form"};
var textbox = new TextBox{Parent=form, Size = form.ClientRectangle.Size, Multiline = true};
textbox.Text = "Your Text";
form.ShowDialog();
You'll also need this using System.Windows.Forms somewhere and reference to System.Windows.Forms.dll
Related
I'm currently struggling with a button I want to add dynamically inside a RichTextBox.
The main issue is that I can't seem to get the location down properly (Location X & Y) also that the Text adjusts with Form Changes but the location of the Buttons won't.
The concept behind this is that I want to be able to write RTF Documents and include Button Clicks for certain Functions (Copy for now) without having to adjust the program every time.
My idea was to have a very specific Pattern -> [Copy|WHAT-TO-COPY] and replace every occurrence of this with a [C] Button in the application.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadRTF();
AddButtons();
}
private void LoadRTF()
{
richTextBox1.LoadFile("RTF Path");
richTextBox1.ReadOnly = true;
}
private void AddButtons()
{
String Text = richTextBox1.Rtf;
richTextBox1.ReadOnly = false;
foreach (Match CopyMatch in Regex.Matches(Text, #"\[Copy\|.*\]", RegexOptions.IgnoreCase))
{
string CopyString = CopyMatch.Value;
var CopyPosition = richTextBox1.GetPositionFromCharIndex(richTextBox1.Find(CopyString));
Button Copy = new Button
{
Text = "Copy",
Size = new Size(20, 23),
Location = new Point(CopyPosition.X, CopyPosition.Y)
};
Copy.Click += (_, args) =>
{
Clipboard.SetText(CopyString.Substring(6, CopyString.Length - 7));
};
richTextBox1.SelectionStart = richTextBox1.Find(CopyString);
richTextBox1.SelectionLength = CopyString.Length;
richTextBox1.SelectedText = "";
richTextBox1.Controls.Add(Copy);
}
richTextBox1.ReadOnly = true;
}
}
The first issue is that this method apparently doesn't work to get the proper X,Y values for the Button Creation. It seems the values don't align with the found PositionFromChar(Index).
Am I headed in the entirely wrong direction is this a proper start? What am I missing?
Also, I'm still completely new to programming so sorry if this is a total mess.
I create a desktop app c# where i use some references :
using Microsoft.Toolkit.Uwp.Notifications;
using System.Windows;
using Windows.ApplicationModel.Activation;
using Microsoft.QueryStringDotNET;
And where i added some reference related to UWP application :
- Windows.System
- Windows.UI
- Windows.data
- Windows.Foundation
- Windows.ApplicationModel
Then i created a simple procedure to create and show my toast notification with the followin code :
private void Button_Click(object sender, RoutedEventArgs e)
{
var toastContent = new ToastContent()
{
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = "Surface Launch Party"
},
new AdaptiveText()
{
Text = "Studio S / Ballroom"
},
new AdaptiveText()
{
Text = "4:00 PM, 10/26/2015"
}
}
}
},
Actions = new ToastActionsCustom()
{
Inputs =
{
new ToastSelectionBox("status")
{
DefaultSelectionBoxItemId = "yes",
Items =
{
new ToastSelectionBoxItem("yes", "Going"),
new ToastSelectionBoxItem("maybe", "Maybe"),
new ToastSelectionBoxItem("no", "Decline")
}
}
},
Buttons =
{
new ToastButton("RSVP", "action=rsvpEvent&eventId=63851")
{
ActivationType = ToastActivationType.Foreground
},
new ToastButtonDismiss()
}
},
Launch = "action=viewEvent&eventId=63851"
};
Windows.Data.Xml.Dom.XmlDocument xmldoc = new Windows.Data.Xml.Dom.XmlDocument();
xmldoc.LoadXml(toastContent.GetContent());
var toast = new ToastNotification(xmldoc);
toast.Activated += OnActivated1;
// Create the toast notification
//var toastNotif = new ToastNotification(xmlDoc);
// And send the notification
ToastNotificationManager.CreateToastNotifier("Test").Show(toast);
Now my problem is that i don't know how to retrieve the item i selected in the list :-(
I created an procedure based toast.Activated event :
void OnActivated1(ToastNotification sender, object e)
{
var toastActivationArgs = e as ToastNotificationActivatedEventArgs;
}
With this event, i can retrieve the argument (to know the button i clicked on) but getting the UserInput thanks to the class "ToastNotificationActivatedEventArgs" seems to be not possible...
Do you know if it's possible ? Is it a limitation of using reference UWP in a desktop app ?
Thank you very much !
Vincent
If you're building a Win32 Desktop app using the Desktop Bridge, you currently cannot use inputs and selection boxes in your toast, as there's no way to retrieve the input.
If you're building a normal Win32 app, you must set up a COM server to handle activation, which will include the inputs that the user selected. This quickstart explains how to set this up for normal Win32 apps. Plus, this will also allow your toasts to persist in Action Center, so if the user missed the popup, they can still access your toast from Action Center.
thank you for your answers.
The issue i have with my sub OnActivated :
void OnActivated1(ToastNotification sender, object e)
{
var toastActivationArgs = e as ToastNotificationActivatedEventArgs;
}
is that the "e" object is recocgnized as a Windows.UI.Notifications.ToastActivatedEventsArgs and not as "ToastNotificationActivatedEventArgs" from Windows.ApplicationModel.Activation (where the properties Kind, UserInput.. should be very useful for me to get the content of selected item).
In my OnActivated1 sub, the var toastActivationArgs value equals to null because it cannot be converted to ToastNotificationActivatedEventArgs.
During my test the e.arguments equals to string "action=rsvpEvent&eventId=63851" but there is no XML returned. This is the only property available of the object e. (but this is useful to get the button where i clicked on)
I'm going to check the link from Andrew Bares to try to setup a COM server but i can see that's in c++ language..
Thank you !
The ToastNotificationActivatedEventArgs e.Arguments should be an xml string with what you need ready to parse.
First look at the string and see if it has what you need. Then go about using XMLReader or something to parse it.
Could you post the string you get?
Okay, so i am working in xna and i want to open this textfile which should open in a textfile. Here is the code:
if (Keyboard.GetState().IsKeyDown(Keys.G) == true)
{
var fileToOpen = "Name.txt";
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = fileToOpen
};
process.Start();
process.WaitForExit();
}
However an error occurs and cant find the textfile to open. I did this in a normal consol application and just added a new item textfile to the project and it worked fine in the console application, however in XNA it does not seem to work at all.
Also im really not well educated in file directory things and need a quick fix. The text files are placed in this area:
I hope this is of somehelp im trying to give as much information as possible. Just to note streamwriting to textfiles in the directory location shown in the image link works perfectly fine and i just give the name of the file as shown below:
if (player.GetRec.Intersects(map.sharkRec))
{
using (StreamWriter writer = new StreamWriter("CurrentScore.txt"))
{
writer.Write(time);
}
player.Position = new Vector2(64,100);
mCurrentScreen = ScreenState.leaderboard;
}
However it just didt seem to work when i want to open the textfile in notepad and allow for typing to be done in the textfile in notepad. The reason why i want to open a text file for typing is the user entering there name and i dont have knowledge or the time to do XNA textbox input creation which seems complicated from the tutorials i have seen, which is why i want to open the textfile in notepad for editing. Furthermore this is going to be used on other people's computers so if directorys have to be used i need a directory that will work on other computers as well as my own, just to note directory entering seems to confuse me.
Hope i have given enough information and i really hope someone can help this beginner out here :)
For this to work, your code should be something like this:
using(StreamWriter ...)
{
show textbox so the user can see what he's typing
for each keypress add the letter
exit on ESC button (for example)
delete char on Backspace
etc...
}
Now, I personaly don't recommend this type of code. Open the file, do what you have to do with it and close it. The code below is how I programmed textbox for my game. I hope it helps (you could say this is more a little tutoial for better approach to the problem instead an answer to the exact problem you put up for yourself).
namespace Acircalipse.MenuClasses
{
public class TextBox:MenuItem
{
private string originTitle;
public string Text
{
get
{
return title.Replace(originTitle, "").Replace(Menu.separator, "");
}
}
public int index, max;
public TextBox (string Title, string text = "", int MaxCharacters = 14)
{
originTitle = Title;
index = 0;
max = MaxCharacters;
SetText(text);
}
public void SetText (string text)
{
if (text.Length > max) text = text.Substring(0, max);
title = originTitle + Menu.separator + text;
}
public void ChangeIndex (int howMuch)
{
index += howMuch;
ChangeCar(index);
}
public void AddChar (int index = 0)
{
SetText(Text + Menu.Wheel(index));
}
public void ChangeCar (int index)
{
if(Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1) + Menu.Wheel(index));
}
public void DeleteChar ()
{
if (Text.Length > 0)
SetText(Text.Substring(0, Text.Length - 1));
}
}
}
Where the Menu.Wheel(int index) is simply an array of available character for user to type in
public static char Wheel(int index)
{
string charWheel = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int max = charWheel.Length;
while (index > max) index -= max;
while (index ("less than" sign here) 0) index += max;
return charWheel[index];
}
Where Menu.separator is a string ": ".
The code is pretty self explanatory.
Now, when using this class, you'll have to have one bool to see if the user has activated this textbox, and if he has, add text on keypress. If the textbox is inactive, just continue your normal update
What you have to understand is that textbox is a simple string witch is updated when textbox is active, and just showed when not active.
Using this simple and on point definition of TextBox, you can simply create your own class that will work the way you want to.
If this answer helped you resolve your problem, please mark it as the solution.
I just have a question regarding C# list. I am a totally noob when it comes to programming and I'm really sorry for being a bird brainer. I am doing some practice coding and I am creating a simple program that will allow users to input names through textbox1 and then once they press the button1, the names will be stored in a List and will be output on textbox2.
I am having hard time storing the data from textbox1. Checked it online but I haven't found the right article for my concern so I'm trying my luck here.
Sorry guys, I forgot to mention I am using Winforms.
Thank you so much for the fast replies.
assuming winforms...
Drag and drop 2 lists and a button onto your designer.
drag a button onto your designer
double-click your button to automatically create an event
make a list structure somewhere inside your form to store the list
instantiate your list in the form constructor
in the button1_Click event add the text of textbox1 to the list
generate the text of 1textbox2`
here is an example
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
list = new List<string>();
}
List<string> list;
private void button1_Click(object sender, EventArgs e)
{
list.Add(textBox1.Text);
string txt = "";
foreach(string s in list)
{
txt += s + " ";
}
textBox2.Text = txt;
}
}
}
Something like that ?
string name = Textbox1.Text;
ListBox1.Add(name);
If your utilizing a traditional Windows Form Application; I'm not sure you meant to store the data in another Text Box. But a List Box may be more along your goal.
Drag the following: Textbox, Second Textbox, Listbox, and Button from the toolbox to your Form.
Adjust them however you would like, treat them like a canvas for a painting.
Once it appears to be configured how you would like double click the Button.
At this point Visual Studio will leave Designer View and go into Code View. So you'll be able to see the code. It will automatically place you in the Button code block.
These blocks are quite important, as you progress you'll notice how C# is structured.
private void button1_click(object sender, EventArgs e)
{
// Logic to add will go in here.
}
What does this mean?
Private : Is the modifier, it means it is restricted to this class.
Void: Means it isn't asking for a return type.
button1_click: That is the name of the button, you can change that within it's Properties. It's good practice to name the component infront so you know what your working with.
What that entire block is, is an Event. So when it is clicked it will perform an action. That is what it means; so this is where your goal is implemented:
private void btnAddToList_Click(object sender, EventArgs e)
{
// Test to ensure it isn't null.
if(txtAddText.Text != String.EmptyOrNull)
{
// Declare a variable with the initial textbox value.
string txtVar = txtAddText.Text;
// Has the second textbox inherit value from other Textbox.
txtNewText = txtVar
// Now Add it to a Listbox.
lstContainer.Items.Add(txtAddText.Text + DateTime.Now());
}
else
{
// Null or Empty Character, Error Message.
MessageBox.Show("Invalid Entry, please enter a valid entry");
}
}
That will provide the fundamental knowledge, but as you can see from your other examples they do it differently. You'll notice that bugs can exist in such logic if you aren't careful. Which you'll learn to identify based on the structure you configure.
Hopefully this is helpful, and it looks like a lot of others did some terrific post for you as well.
Happy coding.
You could use something simple as this:
private void button1_Click_1(object sender, EventArgs e)
{
string[] names = textBox1.Text.Split(new string[] { " ", Environment.NewLine, "," }, StringSplitOptions.RemoveEmptyEntries);
//you can add more parameters for splitting the string
textBox2.Text = string.Join(",", names);
//you can replace the comma with something more suitable for you
}
The first line splits the string that you entered in the textBox1 (hence names separated by newlines, blank characters or commas) into array of string (instead of list that you requested) and the second line joins the strings into one big string of names separated by commas and puts it into the textBox2
This is very simple.
List<string> mylist=new List<string>();
mylist.Add(textbox1.Text);
textbox2.Text=mylist[mylist.Count - 1]
First you create a list of string objects.
Then add the text from textbox1 to the end of the list.
Then get the last element you added from the list by getting the length of the list and subtracting 1 since in C# collections are 0 based and the first element is [0] and not [1].
Within the button1 click listener (if you don't have this hook go into the GUI builder view and double click on the button, it will automatically create and register the listener for you), add the following code;
textbox2.Text = textbox1.Text; // set tb2 = tb1
textbox1.Text = System.String.Empty; // clear tb1
Now, in your post you say store the data in a list, but you don't specify how the user is to input that data so it's hard to give you a specific answer. If the names are say separated by commas to get an array with all the names you could simply do;
string[] names = textbox1.Text.Split(',');
However, from your post it doesn't seem you want to store the data in a list at all. If you just want the input in textbox1 to be displayed in textbox2 upon clicking the input button then use use the first code snippet. If you go the second route, you'll have to convert the array back into a single string. This can be done easily with a for loop.
string result = System.String.Empty;
for (int i = 0; i < names.Length; i++)
result = result + names[i] + " ";
To make textbox2 display what's in textbox1 and display the number of names;
textbox2.Text = textbox1.Text; // set tb2 = tb1
string[] names = textbox1.Text.Split(','); // i use a comma but use whatever
// separates the names might just want ' ' for whitespace
textbox1.Text = System.String.Empty; // clear tb1
MessageBox.Show("You entered " + names.Count.ToString() + " names."); // show the names count
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShowAllSaveNameAndCountApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> ourList=new List<string>();
string txt =" ";
private void buttonSave_Click(object sender, EventArgs e)
{
ourList.Add(textBoxEntryName.Text);
foreach (string s in ourList)
{
txt+= s+ "\n ";
}
textBoxEntryName.Clear();
ourList.Clear();
}
private void buttonShowAllName_Click(object sender, EventArgs e)
{
textBoxShowName.Text = txt;
}
}
}
I'm calling a public method from another class. It takes in a List as a parameter, and goes through the list printing out each item into a text field. The problem is the text field is remaining empty!. I've checked that the list is populated by outputing the item to the console before I put it into the text box, and the text is coming up fine there.
The list contains strings, and should output each string to the textfield followed by a semi colon.
This is the method which is being called:
public void fillAttachment(List<string> attachList)
{
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
txtAttach.Text += attachList[i] + ";";
}
}
I would solve it in this way:
foreach(var attach in attachList)
{
Console.WriteLine(attach);
txtAttach.AppendText(string.Format("{0};", attach));
}
Setting the text property on a text box and it not displaying could be one of the following:
You are not looking at the same control as you are setting the text in
Could you have instantiated a second copy of the form object and it is this form that you are setting the txtAttach text property in?
Could the control that you are expecting to be populated be a different one? Right click the text box that you want the text to appear in click properties and check the name.
Something else is clearing the textbox after you set it
Right click the txtAttach.Text and click Find All References, this will show you all the places that the Text property is referenced - written and read - in your project. This is a very useful way to locate other interaction with this control.
Fomatting is making the text box appear empty
Is the Font too small, or in the same colour as the background. Can you select the text in the text box?
The easiest way to test all of the above is to create a new text control on your form with a different name, change your code to populate it, check that it is indeed populated, then replace the old one.
As an aside, you could also reduce the code with a single line as follows:
public void fillAttachment(List<string> attachList)
{
txtAttach.Text = String.Join(";", attachList.ToArray());
}
Although this obviously skips out the console write line function.
Not sure why yours doesn't work but I would have done it like this...
public void fillAttachment(List<string> attachList)
{
string result = "";
//OR (if you want to append to existing textbox data)
//string result = txtAttach.Text;
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
result += attachList[i] + ";";
}
txtAttach.Text = result;
}
Does that work for you? If not then there is something else very wrong that is not obvious from your code