Create Save And Load Functionality For A Winform [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a winform with 5 text boxes and 2 data grids. I need a way of being able to press a button (or adding a menu at the top with a file button and select save from there) and save all of the values to a file that the user selects location/name for. Then I need a button (or again a menu option) to load the file that was previously saved and all the values from the "save" will be generated on screen so that it looks as if you just input all values.
How is this achieved in VS2017?

You describe your problem and your answer already. You can just straight forward implement like that: Save the data to a file, then when press the Button 2, load data from that file to form.
Other approach, you can have global variable, when press Button 1, you save data to that variable, then when Button 2 pressed, you load this variable's value to form.
public class UserData
{
public string Location { get; set; }
public string Name { get; set; }
}
Then in your form:
public partial class Form1 : Form
{
static List<UserData> savedData;
public Form1()
{
InitializeComponent();
savedData = new List<UserData>();
}
private void button1_Click(object sender, EventArgs e)
{
//This is for example only, you get data then save it like this
savedData.Add(new UserData
{
Location = "US",
Name = "Boston"
});
savedData.Add(new UserData
{
Location = "US",
Name = "Texas"
});
}
private void button2_Click(object sender, EventArgs e)
{
//This is for example only, you WRITE your own business here
foreach (var item in savedData)
{
label1.Text = item.Location;
label2.Text = item.Name;
}
}
}

Related

How to add a money value to a Button in c# winforms? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am making a Point of Sale (order taking) system. I would like to know how to assign a value to a button in c# in Winforms. For example, when you press the "meat lovers pizza" button, it appears in a Listbox with the name of the food item on the button and the price of the button.
To just add pizza name and price to ListBox all you need is to handle button click (create new handler by double clicking a button in form designer).
private void PizzaButton_Click(object sender, EventArgs e)
{
MyListBox.Items.Add("Meat Lovers Pizza - $12");
}
But I guess you want to store orders somehow. One simple idea is to create a pizza class and store all ordered pizzas in some property.
public partial class Form1 : Form
{
public List<Pizza> Pizzas { get; set; }
public Form1()
{
InitializeComponent();
}
private void PizzaButton_Click(object sender, EventArgs e)
{
MyListBox.Items.Add("Meat Lovers Pizza - $12");
Pizzas.Add(new Pizza()
{
Name = "Meat Lovers Pizza",
Price = 12
});
}
}
public class Pizza
{
public string Name { get; set; }
public double Price { get; set; }
}
This should get you started. You can later generate some kind of orders summary from that list of pizzas. Maybe create a list of available pizzas etc. Good luck.

Form 2 textbox displays in form 1 listbox

I currently have two forms, one to display information when a user is selected from the listbox(the listbox lists names, when selected it will fill a few textboxes I have, one for city and another for address), the second form allows me to input the information for the user, which when I click submit will display them in my listbox on form1. Currently I am able to add the user from my second form to my first form into the listbox, but I am having issues filling their information in the textbox whenever I click on their names in my listbox.
As of now I have tried implementing different code snippets, but being a beginner I'm not sure how to do this.
My first form is as follows
public Form1()
{
InitializeComponent();
}
private void ButtonAddUser_Click(object sender, EventArgs e)
{
Form2 form = new Form2(textBoxFirstName.Text, listBoxUsers);
form.Owner = this;
form.ShowDialog();
form.Show();
}
private void listBoxUser_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxUser.SelectedIndex != -1)
{
User selected = (User)listBoxUser.SelectedItem;
textBoxStreet.Text = selected.Street;
textBoxCity.Text = selected.City;
}
}
My second form where I add the users information is as follows
public partial class Form2 : Form
{
private ListBox _listBoxUsers;
public Form(string value, ListBox listBoxUser)
{
InitializeComponent();
value=($"{textBoxFirstName.Text} {textBoxLastName.Text}");
_listBoxUsers = listBoxUsers;
}
private void ButtonSubmit_Click(object sender, EventArgs e)
{
_listBoxUsers.Items.Add($"{textBoxFirstName.Text}
{textBoxLastName.Text}");
this.Close();
}
}
And my Class where I am trying to store the textbox information
public class User : EventArgs
{
public string Street {get; set;}
public string City {get;set;}
public User(string street, string city)
{
Street = street;
City = city;
}
}
In Short: I'm trying to save information from my second form into my class, and when I select a user from my listbox it will display his street and city into textboxes (my listbox and textboxes are both on my first form.).
Thanks for any help
In the second form you should be creating User object and fill the details like street and city .
private void ButtonSubmit_Click(object sender, EventArgs e)
{
User user = new User(textBoxFirstName.Text, textBoxLastName.Text);
_listBoxUsers.Items.Add(user);
this.Close();
}
Since Listbox.Items expecting object type, you can add anything which is derived from System.Object. But in the form1 you have created list with User Objects and during selected index changed you are type casting as User Object. But in the form2 you have not actually inserted User object during the submit button click .
Because of this, i think you are facing this problem . Try with above code and check
I would suggest decoupling state management from the presentation. For example, try to create a separate class for User that is not derived from EventArgs. And manage its state inside a separate class - for start int will be in-memory storage. But as you flesh out your implementation you can latter move your data to Database with ease as it will not rely on UI and its elements for storage and management.

How to fully pass a List? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I use a list to contain data parsed from an XML file, using strings as its members:
public class ServerList
{
public string ServerName { set; get; }
public string ServerReboot { set; get; }
public string ServerShutdown { set; get; }
public ServerList()
{
ServerName = "";
ServerReboot = "";
ServerShutdown = "";
}
}
From the main form I launch an editor form and pass the list into it. On this editor form the user is able to add or remove entry entries form the list, as well as make changes to parts of the list. If they click the OK button I want to be able to pull the list form the editor form back into the main form, but if they click Cancel I want these changes to get dropped. This is the way the editor form is pulled up:
private void mnuEdit_Click(object sender, EventArgs e)
{
frmEditor theEditor = new frmEditor();
theEditor.updatedServerList = theServerList;
DialogResult res = theEditor.ShowDialog();
if (res == DialogResult.OK)
{
theServerList = theEditor.updatedServerList.ToList();
SetupFilters(GroupOrBatch.Group);
// other processing to update the main form from the updated list
}
}
And on the Edit form this is how it is received:
public partial class frmEditor : Form
{
private List<ServerList> myServerList = new List<ServerList>();
public List<ServerList> updatedServerList
{
get { return myServerList; }
set { myServerList = value.ToList(); }
}
....
What I am finding is that while the list structure appears to be copied to the new variable, the actual data is still linked to the original list. Even if the user clicks Cancel, and the modified list is not copied back to the original, the original has already been changed.
This leaves me with one of two options - either I can find some way to do a full deep clone of the list to a new one (which can be dropped upon an Cancel), or I remove the Cancel button entirely and have all edits be live.
class is stored by reference inside the list. The .ToList() merely makes a shallow copy of the list with the same references pointing to those ServerList. Therefore by making any changes on the shadow copy, the original list is still affected.
You need to make a deep copy the list, and to pass them around for editing them :
ServerList::Clone
public class ServerList
{
// properties...
// ctor...
public ServerList Clone()
{
return new ServerList
{
ServerName = ServerName,
ServerReboot = ServerReboot,
ServerShutdown = ServerShutdown,
});
}
}
mnuEdit_Click
private void mnuEdit_Click(object sender, EventArgs e)
{
frmEditor theEditor = new frmEditor();
theEditor.updatedServerList = theServerList.Select(x => x.Clone()).ToList(); /*changed */
DialogResult res = theEditor.ShowDialog();
if (res == DialogResult.OK)
{
theServerList = theEditor.updatedServerList; /* changed */
SetupFilters(GroupOrBatch.Group);
// other processing to update the main form from the updated list
}
}
Note: The .ToList() on updatedServerList.get is not necessary.
As an alternative, since your data set is very small, convert your data to a struct:
public struct ServerList
{
public string ServerName { get; private set; }
public string ServerReboot { get; private set; }
public string ServerShutdown { get; private set; }
public ServerList(string name, string reboot, string shutDown)
{
this.ServerName = name;
this.ServerReboot = reboot;
this.ServerShutdown = shutDown;
}
}
A struct is a value type (as opposed to a reference type), and value semantics will apply to it. Consider the following:
var listA = new ServerList("Foo", "Daily", "Never");
var listB = listA;
A copy of listA and all of its values is stored in listB, not a reference. For the strings, copies of the references are made, but strings are immutable anyway, so there's no issue there.
CON: structs are supposed to be immutable. Once you initialize them, you can't change their data. Consider that before adopting this solution.

C# using MVVM - Difficult Behavior [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
After spending hours (maybe days) grinding trying to solve, I decided to put my faith in your knowledge. I want to implement this behavior (blue):
So in the loginButton I fire a command that is handled in the loginViewModel in this handler I do some verifications to a webservice and using that answer I want to open a new Window sending an User (class). How can I do this?
I've tried messaging, I've tried a lot of things. In code behind is something like this that I want to do using MVVM architecture.
LoginView Code-Behind
button_OnClick(){
// Checking stuff
var u = //from the server;
PrincipalView pv = new PrincipalView(u);
pv.Show();
this.Close()
}
In the PrincipalView Code-Behind:
public PrincipalView(User u){
// Yey, I have the user
}
I have done that by using a custom window service class like following:
class WindowsService
{
private static LoginWindow loginWindow{ get; set; }
private static UserWindow UserWindow{ get; set; }
public void ShowLoginWindow(LoginViewModel loginViewModel)
{
LoginWindow = new LoginWindow
{
DataContext = loginViewModel
};
LoginWindow.Show();
}
public void ShowUserWindow(UserViewModel userViewModel)
{
UserWindow = new UserWindow
{
DataContext = userViewModel
};
LoginWindow .Hide();
UserWindow.Show();
}
}
So you declare an instance of WindowsService in your LoginViewModel, and when your logic find the user you create an instance of your UserViewModel and call windowsService.ShowUserWindow(userViewModel). In order to use this properly, you have to modify your App.xaml.cs file like this:
public partial class App : Application
{
private void App_OnStartup(object sender, StartupEventArgs e)
{
var loginViewModel = new LoginViewModel();
loginViewModel.StartLoginWindowService();
}
}
The method StartLoginWindowService() may look like this:
public void StartLoginWindowService()
{
WindowsService.ShowLoginWindow(this);
}
Please let me know if this helps
Explaining where to create UserWindowViemodel
Suppose the following method in your loginViewmodel
public void Loging(string name, string pass){
var isAllowed(name, pass); //Check if user exists and if pass is correct
if(!isAllowed) return; //we return if user is invalid
var wService = new WindowsService();
var myUser = new UserWindowViewModel(name){
//you set all proeperties you need here
}
wService.ShowUserWindow(myUser);
}
You probably need a service which will open a window when you pass it a ViewModel.
Basically, you will have a ViewLocator which will find the specified View for you when you give it a ViewModel. The UIService have methods such as Show and ShowDialog to which you can pass any ViewModel. These methods will then open the registered view and also assign a new UIService for the newly created ViewModel.
I have described the process in detail in this answer.

Display datagrid based on one filter in wpf [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have datagrid and one value slider.I have three columns .Three columns like name,age and telephone number.Filter value is set to age.If i change slider value that is filter(age) based on filter DataGrid needs to display the data.I am using observable collection.
I think i understood what you want exactly.
Assuming that the name of your Data Grid is "MyDataGrid" and it's data source is bound to a class "MyDataGridItem" with this structure
public class MyDataGridItem
{
public string Name { get; set; }
public int Age { get; set; }
}
Subscribe the ValueChanged event of the slider and get the value and use LINQ where query to filter your results.
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
var sliderValue = (int) MySlider.Value;
MyDataGrid.ItemsSource = students.Where(item =>item.Age<sliderValue);
}

Categories

Resources