How to add entries every time a button is pressed - c#

I am making a mobile app using Xamarin Forms and I am writing all of my code including the visual aspects in c# (in the .cs files).
Essentially I need to be able to add a new entry every time a button is pressed and then get the text entered into said entry.
Right now I can create a new Entry and give it a name that I can use to reference it:
private Entry entry1;
Layout.Children.Add(entry1 = new Entry
{
//entry code
});
//when some button is pressed
string entry1Text = entry1.Text;
I want to make it so that every time the user presses a button, it creates a new entry, but I also need to be able to get the text from it. How can I make it so that it creates a new entry with a new name like entry2, entry3, etc... without manually writing out like 10 entries and then making them visible? I need to do this because I don't know how many entries the user will add (could be more than 10).
int numberOfEntries = 1;
void addEntry_Clicked(object sender, EventArgs e)
{
string entryNumber = numberOfEntries.ToString();
//the following 2 lines are what doesn't work with the name of an entry, but is what I want to do
private Entry entry + entryNumber;
Layout.Children.Add(entry + entryNumber = new Entry
{
//entry code
});
numberOfEntries+=1;
}
//some button is pressed
string entryText = (entry + entryNumber).Text;
The problem is I can't add a number to the name of an entry like entry +"2"
Is this even possible for me to do?

you need to keep a separate data structure to track your controls, like this
Dictionary<string,Entry> entries = new Dictionary<string,Entry>();
private void AddEntry(string name)
{
var entry = new Entry();
myLayout.Children.Add(entry);
entries.Add(name,entry);
}
then you can get their value like this
var text = entries["entryA"].Text;

Related

Update ListBox from another class not working

I have a ListBox that is populated with entries from a folder consisting of text files (the list box is taking the names of the files only). I have trouble getting the list box to refresh every time I add files. You add files/errands by pressing a button in the main program, which brings out a second window in which you write your errand and choose its priority (low, medium or high).
The desired effect would be that the list box would update itself when adding new text files/errands, to include it, however, this is not the case at the moment, and I've tried following examples on the net by using DataStore and Binding among others, but none have worked so far. The main program looks like this:
P.S. The program is half-Swedish, but essentially, "Skapa lapp" = "Create errand", which is the only important one here.
And this image below is just to show you how the list box and the errands/text files work together (the text files are added to the list box by a foreach loop).
When creating a new errand (Skapa lapp-button), you will be presented with a new window:
When writing your new errand in this window and choosing a priority level then pressing "Create errand" (or Skapa lapp), the following will happen on that button click (simplified version):
private string mappNamn = #"C:\Errands\";
Lapphantering uppdateraFönster = new Lapphantering();
private void buttonSkapaLapp_Click(object sender, EventArgs e)
{
try
{
//When choosing the low priority radio button, do this:
if (radioButtonLågPrio.Checked)
{
using (var file = new StreamWriter(Path.Combine(mappNamn, "1 - " + textBoxLappText.Text + ".txt")))
{
uppdateraFönster.listBoxLappar.Items.Add(textBoxLappText.Text);
uppdateraFönster.Update(); //This doesn't work.
uppdateraFönster.Refresh(); //Nor does this.
}
}
Back over to the main window (Lapphantering), the list box is only updated when you restart the application all over again and let the main program add the files by initializing the component:
public Lapphantering()
{
InitializeComponent();
//For each file, add new files to the list box.
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Errands\");
FileInfo[] Filer = dinfo.GetFiles("*.txt");
mappNamn = dinfo.FullName;
foreach (FileInfo file in Filer)
{
listBoxLappar.Items.Add(Path.GetFileNameWithoutExtension(file.Name));
}
}
So, how can I refresh/update the list box every time I add a new errand/text file without having to restart the application each time?
Theproblem is that you are creating a new instance of Lapphantering and editting the value in there. Change this in your Program cs:
public static Lapphantering mainForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
mainForm = new Lapphantering(); // create instance of Lapphantering
Application.Run(mainForm);
}
then in your other window do this:
if (radioButtonLågPrio.Checked)
{
using (var file = new StreamWriter(Path.Combine(mappNamn, "1 - " + textBoxLappText.Text + ".txt")))
{
Program.mainform.listBoxLappar.Items.Add(textBoxLappText.Text);
Program.mainform.listBoxLappar.Update();
Program.mainform.listBoxLappar.Refresh(); // access mainform in Program
}
}
this should work your are working on one object in the program.cs
You are looking for a file system monitor. This might help: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

How to load the correct image from my database to the correct item when I click on my pin?

So I have a map in my code with multiple pins. When I click on a pin I get to a newpage with the pintitle. That works but If I want to add an image/and or description to that same page (that I also store on my database, parse) it doesnt work as I only get the topimage stored in the database on every different pin i click.
string picture;
string theDescription;
var getItems = await parseAPI.getInfo (Application.Current.Properties ["sessionToken"].ToString ()); //I load my data.
foreach (var currentItem in getItems["results"])
{
var prodPic = "";
if(currentItem["image"] != null)
{
prodPic = (string)currentItem ["image"] ["url"];
}
picture = prodPic; //i add the picture.
theDescription = currentItem ["description"].ToString (); // i add the descrption
dName = currentItem ["name"].ToString (); //and the title
var pin = new Pin ();
pin.Position = new Position (16,13);
pin.Label = dName; //and then i connect my title here so it works, but how should I do it with my picture + description?
pin.Address = "click for info";
pin.Clicked += onButtonClicked1;
theMap.Pins.Add (pin); //adding my pins to my map.
}
void onButtonClicked1 (object sender, EventArgs e)
{
Pin pin = (Pin)sender;
Navigation.PushAsync (new DetailPage (pin.Label, picture, theDescription )); //label works, so every pin get a unique label, but picture + the description remains the same inside the item i enter.
}
so It works with the title, and that is because I have connected the pin to my onbuttonclicked1 (pin.label) function I assume? so I how should I do it with my image + description so the pin does not get the same picture + description on every pin i enter
UPDATED IDEA:
new List <String> ourItems = new List<String> ();
ourItems.Add (theDescription);
ourItems.Add (picture);
Like this? and then somehow connect them into my OnButtonClicked1 function?
You are running a foreach loop which repeatedly sets the same "picture" variable. That is, every time you iterate, you are setting the "picture" and "description" variables to whatever value is relevant for the current iteration without actually persisting any of the previous values anywhere.
Your loop would look something like this:
Iteration one: picture = "pictureOne.png";
Iteration two: picture = "pictureTwo.png";
Iteration three: picture = "PictureThree.png";
...etc
What this means is that by the time your loop ends, you will have reset your imagine multiple times, with the variable retaining its last set value (in the above example that would be "pictureThree.png"
One way (not necessarily the best, mind you) would be to have an empty list, which you then populate from within the loop.

How can I clear textboxes so submit button can be re-used?

I am making a program for school in C#, and its purpose is to allow the user to enter film data, which it then puts into an object for that film. It will also include other functionality such as the user being able to search for a film (it says I have to make 3 film objects and store them in an array all being input by the user).
I have created the first part of the Windows Forms application and it is a screen that gets all the input from the user like the name, director, rating, etc... and there is a submit button which creates the object. Is there a way, without creating a new form, to use the same screen and clear the textboxes so that when the submit button is clicked again it creates a NEW OBJECT like 'film2'?
Here is my code for the submit button:
private void button1_Click(object sender, EventArgs e)
{
int year = Convert.ToInt32(dBox_year.Text);
Film film1 = new Film(tbox_name.Text, tbox_director.Text, tbox_actor1.Text, tbox_actor2.Text, year, tbox_rating.Text);
filmArray[0] = film1;
}
So, you see how I would like to have the textboxes on the main screen clear themselves, and reuse the same screen but only it would be 'Film film2 = ...' etc.
This is not an assesed piece and we haven't covered this in class yet so I have tried.
private void button1_Click(object sender, EventArgs e)
{
int year = Convert.ToInt32(dBox_year.Text);
Film film1 = new Film(tbox_name.Text, tbox_director.Text, tbox_actor1.Text, tbox_actor2.Text, year, tbox_rating.Text);
filmArray[0] = film1;
//clearing after adding to array
//or you can just use .Clear() method
tbox_name.Text = String.Empty;
tbox_director.Text = String.Empty;
tbox_actor1.Text = String.Empty;
tbox_actor2.Text = String.Empty;
tbox_rating.Text = String.Empty;
}
tbox_name.Clear() - Clears all text from the text box control.(Inherited from TextBoxBase.)
You could use a List instead of an Array, declared at form level:
private List<Film> filmList = new List<Film>();
Then your button click even would look like
private void button1_Click(object sender, EventArgs e)
{
int year = Convert.ToInt32(dBox_year.Text);
filmList.Add(new Film(tbox_name.Text, tbox_director.Text, tbox_actor1.Text, tbox_actor2.Text, year, tbox_rating.Text));
tbox_name.Text = string.Empty;
tbox_director.Text = string.Empty;
tbox_actor1.Text = string.Empty;
tbox_actor2.Text = string.Empty;
tbox_rating.Text = string.Empty;
dBox_year.Text = string.Empty;
}
Here you're creating a new Film object and adding it straight away to the list of films, and then clearing the text boxes afterwards.
If there's a specific reason you need an array, then you can always later do
filmList.ToArray()
Hope this helps!
When Submit button is clicked you want to add the object at the end of the array, not put it at the first position.So you will need an extra variable named, let say, filmCount, which you initialize with 0 and increment on each submit.
Film film1 = new Film(tbox_name.Text, tbox_director.Text, tbox_actor1.Text, tbox_actor2.Text, year, tbox_rating.Text);
filmArray[filmCount++] = film1;
then you clear the texboxes
foreach(TextBox TB in this.Controls)
{
TB.Text = "";
}

C# listbox add data from another form

I'm a C# student and I'm a little stuck at on my midterm project.
I dropped my project and spec here: https://www.dropbox.com/sh/eo5ishsvz4vn6uz/CE3F4nvgDf
If you run the program, it will come to the last area I left off at..
private void btnAddScore_Click(object sender, EventArgs e)
{
for (int i = 0; i < 3; i++)
{
tempScore = Convert.ToDecimal(txtScore.Text);
Form1.scoreList = tempScore; (was Form1.scoreList[i] = tempScore;)
}
txtScoresList.Text += Convert.ToString(tempScore) + " ";
}
There's a main form, a secondary add form, and a third and fourth form, all the controls are in place, just the wiring is what's left over.
(1) In the above code, there are supposed to be 3 scores passed to the main form, which, along with a student name string, are to populate the ListBox on the main form. I can't figure out how to access that ListBox, anytime I type "listStudents" nothing happens.
(2) I'm also not sure how to limit an input of only 3 scores when I'm clicking the "add" button 1 time, which means I know my for loop is probably completely wrong. I don't know if I should save those scores to an array, list, or individual vars, being that it can be 3 (or more, but 3 is fine) scores.
(3) When I hit "OK" on the AddNewStudent form, do I write my code there to populate the main form ListBox, or does it go in the main form?
Update:
private void Form1_Load(object sender, EventArgs e)
{
lbStudents.Items.Clear();
//something like
foreach (decimal i in scoreList2)
{
scoreList = scoreList2.ToString(); //gives me a cannot implicitly convert error
}
lbStudents.Items.Add(tempInfo1 + " " + scoreList2);
}
//I want the listbox to populate like "Name - |100| |90| |80|"
This code seems to me, to be correct, for getting the ListBox populated, but I'm unsure of how to add the entire contents of the list to a string, and then add that to the listbox.
This will get your code building and running.
Change the following declaration in form1
public static decimal[] scoreList = new decimal[3];
to
public static List<decimal> scoreList = new List<decimal>();
and update your btnAddScore_Click handler to
//save scores to temp static var, populate noread txtbox txtScoresList with scores
for (int i = 0; i < 3; i++)
{
//save score to static var for trans-form data sending
tempScore = Convert.ToDecimal(txtScore.Text);
Form1.scoreList.Add(tempScore);
}
The rest is not too difficult, you should be able to work it out.

I need to know how to take the selected item of a comboBox and make it appear on a windows form application?

I have a windows form application with a ComboBox on it and I have some strings in the box. I need to know how when I select one of the strings and press my create button, how can i make that name show up on another windows form application in the panel I created.
Here is the code for adding a customer
public partial class AddOrderForm : Form
{
private SalesForm parent;
public AddOrderForm(SalesForm s)
{
InitializeComponent();
parent = s;
Customer[] allCusts = parent.data.getAllCustomers();
for (int i = 0; i < allCusts.Length; i++)
{
Text = allCusts[i].getName();
newCustomerDropDown.Items.Add(Text);
newCustomerDropDown.Text = Text;
newCustomerDropDown.SelectedIndex = 0;
}
now when i click the create order button I want the information above to be labeled on my other windows form application.
private void newOrderButton_Click(object sender, EventArgs e)
{
//get the info from the text boxes
int Index = newCustomerDropDown.SelectedIndex;
Customer newCustomer = parent.data.getCustomerAtIndex(Index);
//make a new order that holds that info
Order brandSpankingNewOrder = new Order(newCustomer);
//add the order to the data manager
parent.data.addOrder(brandSpankingNewOrder);
//tell daddy to reload his orders
parent.loadOrders();
//close myself
this.Dispose();
}
The context is not very clear to me, but if I got it right, you open an instance of AddOrderForm from an instance of SalesForm, and when you click newOrderButton you want to update something on SalesForm with data from AddOrderForm.
If this is the case, there are many ways to obtain it, but maybe the one that requires the fewer changes to your code is this one (even if I don't like it too much).
Make the controls you need to modify in SalesForm public or at least internal (look at the Modifiers property in the Design section of the properties for the controls). This will allow you to write something like this (supposing customerTxt is a TextBox in SalesForm):
parent.customerTxt.Text = newCustomerDropDown.SelectedItem.Text;

Categories