I have a combo box that holds employee names that are selected by that employee. When I add a name to the combo box with a button click is there a way to keep the name in the combo box for the next time the program is started? Below is my code to add the employee names that I know need to be in the list and then the code to add a name to the combo box.
private void employeeSelect_Load(object sender, EventArgs e)
{
cboEmpName.Items.AddRange(new string[] { "John", "Roger", "Bill", "Jason", "James" });
}
private void addTechbtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtAddTech.Text))
{
cboEmpName.Items.Add(txtAddTech.Text);
txtAddTech.Clear();
MessageBox.Show("Technician has been added");
}
else
{
MessageBox.Show("Enter a name to add to the list");
}
}
If you just want to persist the last value selected by user, UserSetting is the best place to save such values.
Declare user setting values as -
Right click your project >> Navigate to Properties >> Settings
Say the value is EmployeeNameCombovalue, then you can read the value like this -
var empNameVal = Properties.Settings.Default.EmployeeNameCombovalue;
And to save some value in it -
Properties.Settings.Default["EmployeeNameCombovalue"] = cboEmpName.Text;
Properties.Settings.Default.Save();
So next time, when the program stars, you check if the value is there in user setting, if yes, set it to the combobox.
But, if it is not just about saving a particular value, and you want to
save all the drop drop down values, then I suggest to store these
values in some persistent storage like DB, and bind your combobox from
that data. And whenever you add a new value to it, add the same in DB
as well and update your combobox data source.
https://msdn.microsoft.com/en-us/library/x8160f6f%28v=vs.110%29.aspx
There are various options available.
At some point, the answer boils down to a matter of urgency. I'd say you'll end up with these options:
You could store in the local file system, and read them again when form is loaded.
Serialize and store it in the registry (HKEY_CURRENT_USER - user specific)
Store it in the database and retrieve it again when needed.
.NET Application settings, provides the easiest way to access your
settings at runtime (Check this Example).
Related
I'm developing a Windows Form Application for a book seller in my school.
I have a Form for Clients and Books, where I can view the list of clients/books in a DataGridView, Insert new ones to the list, modify, and delete them.
For the Sales form, I need to specify the name of the Client and the Book.
I was thinking on putting a Textbox with a button, and when I click the button, I'll show another window from which I can access the clients/book list, select one from the list and fill the Textbox with his name, or I can directly add a new client, if needed.
Is this possible, or is there a better solution?
You could do something like this:
btnClients_click(object sender, EventArgs e)
{
using (ClientsForms form = new ClientsForms())
{
if (form.ShowDialog() == DialogResult.OK)
{
textBoxClient.Text = form.ClientName;
}
}
}
ClientsForms is your form with Clients. It should have public property ClientName or whatever you need. This property should be set base on value selected in DataGridView.
I've a list of element with a checkbox. The items are available inside a Checkbox, and I save all the checked value inside my settings app, in particular, I've a field called available_countries and I save all the event inside this field.
Essentially when a item is checked a fire the event associated:
private void AvailableCountries_Checked(object sender, RoutedEventArgs e)
{
var item = sender as CheckBox;
if (item.Content.ToString() == "All")//first item of the list need to check all
{
Vm.AvailableNations.Select(c => { c.IsChecked = true; return c; }).ToList(); //Execute the IsChecked update through linq
}
//Check if the checked value is already added in the settings..
var nationsArr = Properties.Settings.Default.available_countries.Split(';');
foreach (var country in nationsArr)
{
if (country == item.Content.ToString()) //Nation already added!
{
return;
}
}
Properties.Settings.Default.available_countries += item.Content.ToString() + ";"; //Separator
Properties.Settings.Default.Save();
}
Now this code working well and is very simple, but I noticed that .Save() at the end slow down the app performance, infact when I click on the first item of the ComboBox that have as .Content : All I need to change all the IsChecked property of all element.
I need also to check if the value is already added in the Settings.
I noticed that if I remove the last line of code I doesn't see the delay time, about 1/2 seconds.
There is a way to improve it?
Well, the settings are stored in an XML file in the user's profile, so yes, whenever you save your settings, a short delay will be there. No way to change that.
A possible solution in your case would be to not save the settings when the check box is checked, but in some other event (like for example an OK button of the settings dialog, etc).
Another solution would be to start a background task that changes the values and saves the settings, but you'd have to make sure this is properly synchronized.
A third solution would be to just change the settings object, but not save until the application is closed. That would slow down the process of closing the application, but ...
I have a web form where I register a new employee. There're 3 parts in the form: Personal info, Address info, Special Status. But there's only one button for the whole form. When I submit the form all the information is updated to the database. So three Update statements are executed against the database. The methods are UpdatePersonalInfo, UpdateAddressInfo and UpdateSpStatus. Is there a way to check if there's been a change in any field in the certain part and run update method only if it's true. So something like this:
if (There's been any change to the personal data of the employee)
{
UpdatePersonalInfo;
}
if (There's been any change to the address information of the employee)
{
UpdateAddressInfo;
}
Sure I know, I can save all the previous values in a session object in PageLoad and then compare them one by one before running the method. But I thought maybe there's a magic way of doing this more easily.
Not sure that this is a better solution than any of the alternatives you already mentioned, but you could create a default handler to attach to the TextChanged, SelectedIndexChanged, etc events of your controls to keep track of which ones have changed.
List ChangedControls = new List(Of, String);
private void ChangedValue(object sender, System.EventArgs e) {
WebControl cntrl = (WebControl) sender;
ChangedControls.Add(cntrl.ID);
}
Then on your button click scour the ChangedControls list for the relevant controls.
Suppose I have one form where a combo box has some options. Now, at the first run of this program, user selects a option from combo box and saved it through a button click or something. Now, If user terminates the application and run again for the 2nd time, is there any way to retrieve the last saved selection?
That means, if you select option1 from the combo box and terminate the application. after some time, you again start the application, now your combo box should show option1 as selected because at the previous session, you selected it.
I hope you'll understand what i think.
Use Settings
// To Load (after combo box binding / population)
private void LoadSelection()
{
int selectedIndex = 0;
if (int.TryParse(Properties.Settings.Default.comboBoxSelection, out selectedIndex))
{
cbMyComboBox.SelectedIndex = selectedIndex;
}
}
// saving on button click.
private void saveButton_Click(object sender, EventArgs e)
{
//set the new value of comboBoxSelection
Properties.Settings.Default.comboBoxSelection = cbMyComboBox.SelectedIndex;
//apply the changes to the settings file
Properties.Settings.Default.Save();
}
See here for more detail.
You have to manually save the value and load it up again when the program starts.
The easy way to do it with Visual Studio is to create a Settings class. In VS, right click your project, click add new, scroll to "Settings File", add. VS will show you a UI where you can create new properties in the settings object that you can chose the name of.
If I create a new property called "ComboboxValue" of type string, I can reference it in the code as Settings1.Default.ComboboxValue = "hello world";
Here's the MSDN on it:
http://msdn.microsoft.com/en-us/library/a65txexh(v=vs.100).aspx
You can add settings
on solution explorer under the project, properties folder
add resource "string" give it a name "selected" for example
then
// this is save button
Properties.Settings.Default.selected = comboBox1.SelectedIndex;
Properties.Settings.Default.Save();
// this is retrieve (use it in window_load event for example)
comboBox1.SelectedIndex = Convert.ToInt32(Properties.Settings.Default.selected);
I want to have a text field in a C# winform application, and the effect I want is that as the user types stuff in the text field, the program searches a database in the background, and then generates a drop down list for the user to choose from ..
Here are two web based examples but do note that my application is winforms based, not web-based .. I just want the same effect, which is why I'm showing these:
cinemasquid.com:
blu-ray.com:
How can I get the same effect for a text field in a C# winform application ?
First you will need to bind TextChanged event on the form. Then when user press any key, you will get the event. Now inside event handler retrieve the string entered by the user, using this string you perform the search (don't do the search on UI thread, else your UI will hang, you can do the search in BackgroudWorker (MSDN)). Once you get the result, bind this result to ListBox.
I had developed one application, which has autocomplete feature. In this if user enter any movie name, matching results use to be displayed in the list box.
Hope this works for you.
If you don't want to code your solution there are a handful of custom controls avaliable via Google search, for example: http://www.dotnetfunda.com/articles/article225.aspx
BUT you should keep response times in mind: if you code a database search everytime the user enters a letter on your textbox, your application could get sluggish and/or unresponsive, depending on number of records on the table, speed of your network connection and a lot of other factors.
Consider preloading a collection of strings (name, titles, whatever it is you want to display on the textbox) on memory and then performing LINQ queries to that in-memory collection to populate the autocomplete part of your control.
As Amar Palsapure say, You need to use TextChanged Event of You DropDown. Also, Background worker will be also welcome.
Here is a short example:
First, we need some data source. In this case, this will be a simple list of strings:
List<string> DataSource = new List<string>
{
" How do I use jQuery to select all children except a select element",
"How can I get the text of the selected item from a dropdown using jQuery?",
"Dropdown menu in IE6 inserting too much width, not dropping-down",
"How to display images within a drop down box instead of text",
"InfoPath 2007 - Populate drop-down list on-the-fly",
"Is there any difference between drop down box and combo box?",
"Drop Down list null value not working for selected text c#?",
"Make drop-downs automatically drop in a loop cycle",
"PHP How can I keep the selected option from a drop down to stay selected on submit?",
"Jquery Issue - Drop down list does NOT show from iPhone/Mobile Devices"
};
next, BackgroundWorker DoWork Event - this is part response for searching valid position in our Data Source:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
String text = e.Argument as String;
List<String> results = new List<string>();
//Code for seraching text - may be diffrent if you have another DataSource
foreach (String dataString in DataSource)
{
if (dataString.IndexOf(text, 0, StringComparison.CurrentCultureIgnoreCase) != -1)
{
results.Add(dataString);
}
}
e.Result = results;
}
You can see, that Result is returning by e.Result, So we need to implement RunWorkerCompleted event too:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
comboBox1.Items.AddRange((e.Result as List<String>).ToArray());
comboBox1.DroppedDown = true;
}
This code will fill our dropDown witch returned values, and show it to user.
Of course, to make this run, you need to call RunWorkerAsync in TextChanged:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
// Save position of cursor, because it like to dissapering.
int cursor = comboBox1.SelectionStart;
//Clearing items in dropDown
comboBox1.Items.Clear();
//Is something was searched before, cancel it!
while (backgroundWorker1.IsBusy)
{
if (!backgroundWorker1.CancellationPending)
{
backgroundWorker1.CancelAsync();
}
}
// And search new one
backgroundWorker1.RunWorkerAsync(comboBox1.Text);
// And bring back cursor to live
comboBox1.SelectionStart = cursor;
}
I hope that helped you