how to save comboxitems using project settings in c# - c#

I want to save my ComboBox items so that after closing the window application i restore previous items in ComboBox which i saved. I Declare Combobox item in project setting of type system.collection.specialized.stringcolection. my code for is given below.
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add(Properties.Settings.Default.combox);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ArrayList arraylist = new ArrayList(this.comboBox1.Items);
Properties.Settings.Default.combox = arraylist;
}
but it show error:
Cannot implicitly convert type 'System.Collections.ArrayList' to
'System.Collections.Specialized.StringCollection'

Get your items from settings and check if they're null. If they're not null, add them to your ComboBox.Items collection.
private void Form_Load(object sender, EventArgs e)
{
var comboboxItems = Properties.Settings.Default.ComboboxItems;
if (comboboxItems != null)
comboBox.Items.AddRange(comboboxItems.Cast<string>().ToArray());
}
When form is closing you need to put your items inside StringCollection format if you're willing to save them. So convert items from your ComboBox.Items collection to string array and add them inside StringCollection. Place your fresh collection into Settings.Default and important thing, don't forget to save changes.
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
var comboboxItems = new StringCollection();
comboboxItems.AddRange(comboBox.Items.Cast<string>().ToArray());
Properties.Settings.Default.ComboboxItems = comboboxItems;
Properties.Settings.Default.Save();
}

Put this in your Form1_FormClosing method:
System.Collections.Specialized.StringCollection items =
new System.Collections.Specialized.StringCollection();
items.AddRange(this.comboBox1.Items.Cast<string>().ToArray());
Properties.Settings.Default.combox = items;

Related

Add and delete text to/from ListBox hosted in WinForm using C#

I am working on a simple application that to add/delete string/s into an array and show that in ListBox.
My code shows only the latest value that was typed into the textBox and
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
List<string> ls = new List<string>();
ls.Add(add);
String[] terms = ls.ToArray();
List.Items.Clear();
foreach (var item in terms)
{
List.Items.Add(item);
}
}
private void Delete_Click(object sender, EventArgs e)
{
}
This code makes no sense. You are adding one single item to a list, then convert it to an array (still containg one item) and finally loop through this array, which of course adds one item to the previously cleared listbox. Therefore your listbox will always contain one single item. Why not simply add the item directly?
private void Add_Click(object sender, EventArgs e)
{
List.Items.Add(textBox1.Text);
}
private void Delete_Click(object sender, EventArgs e)
{
List.Items.Clear();
}
Also clear the listbox in Delete_Click instead of Add_Click.
If you prefer to keep the items in a separate collection, use a List<string>, and assign it to the DataSource property of the listbox.
Whenever you want the listbox to be updated, assign it null, then re-assign the list.
private List<string> ls = new List<string>();
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
// Avoid adding same item twice
if (!ls.Contains(add)) {
ls.Add(add);
RefreshListBox();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Delete the selected items.
// Delete in reverse order, otherwise the indices of not yet deleted items will change
// and not reflect the indices returned by SelectedIndices collection anymore.
for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) {
ls.RemoveAt(List.SelectedIndices[i]);
}
RefreshListBox();
}
private void RefreshListBox()
{
List.DataSource = null;
List.DataSource = ls;
}
The problem with code is quite simple. Instead of adding new item to list your code creates new list with one added item only. I am trying to interpret functions of program and they seem to be:
Enter new text into top level text box.
If Add button is clicked your item goes on top of the list (if it's bottom see end of my answer).
If item(s) is selected in list and Delete is clicked selected item(s) is/are deleted.
To achieve this you should first insert text on top of the list by using Add_Click code, than delete selected items using Delete_Click code. There is additional code to guard against inserting empty or white space only strings plus trimming of leading and trailing white space.
private void Add_Click(object sender, EventArgs e)
{
// Since you do not want to add empty or null
// strings check for it and skip adding if check fails
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text)
{
// Good habit is to remove trailing and leading
// white space what Trim() method does
List.Items.Insert(0, textBox1.Text.Trim());
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Get all selected items indices first
var selectedIndices = List.SelectedIndices;
// Remove every selected item using it's index
foreach(int i in selectedIndices)
List.Items.RemoveAt(i);
}
To complete adding and deleting logic I would add Delete All button which would just call List.Items.Clear(). If you prefer to add text at the end just use Add method form #Olivier Jacot-Descombes answer.
You can use in C#:
private void Delete_Click(object sender, EventArgs e)
{
if(myList.Contains(textbox1.value))//if your list containt the delete value
{
myList.Remove(textbox1.value); //delete this value
}
else
{
//the list not containt this value
}
}
and you can use the same method for validate if a value exist when try to add
private void AddItem()
{
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text))
{
var newItem = textBox1.Text.Trim();
if (!List.Items.Contains(newItem))
{
List.Items.Add(newItem);
// Alternative if you want the item at the top of the list instead of the bottom
//List.Items.Insert(0, newItem);
//Prepare to enter another item
textBox1.Text = String.Empty;
textBox1.Focus();
}
}
}
private void Add_Click(object sender, EventArgs e)
{
AddItem();
}
Private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
AddItem();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Remove every selected item using it's index
foreach(var item in List.SelectedItems)
{
List.Items.Remove(item);
}
}

C# Permanently Add and Save item to combobox

everybody!
I have collection of items in combobox's properties. And I want to add new item in my combobox by writing text in combobox and then use button event:
private void button2_Click_1(object sender, EventArgs e)
{
cbx_unix_dir.Items.Add(cbx_unix_dir.Text);
}
But in next time of starting my programm - my added item doesn't exist in combobox. What do I wrong? I need all added items have been saved in my combobox for ever. May be problem in method InitializeComponents()? May be I have to add event before it?
Thank you very much.
ComboBox has no functionality to save and reload items.
You may store items into .NET Settings file on closing window and reload them on loading form:
private void Form1_Load(object sender, EventArgs e)
{
if (Settings.Default.cboCollection != null)
this.cbx_unix_dir.Items.AddRange(Settings.Default.cboCollection.ToArray());
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ArrayList arraylist = new ArrayList(this.cbx_unix_dir.Items);
Settings.Default.cboCollection = arraylist;
Settings.Default.Save();
}
//A button to add items to the ComboBox
private void button2_Click_1(object sender, EventArgs e)
{
cbx_unix_dir.Items.Add(cbx_unix_dir.Text);
}

Edit Items in a ListBox

I am creating a program using WinForms so users can input info into textboxes on one form which then are saved into a Listbox on another form. I would like to be able to edit the items saved in the listbox by opening the original form on a button click. Really struggling with it as I can't think of the code and I can't seem to find a solution.
My Code:
private void btnAdd_Click(object sender, EventArgs e)
{
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.ShowDialog();
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
listBoxRooms.Items.Add(newRoomDisplayForm.value);
}
newRoomDisplayForm.Close();
}
private void btnRemove_Click(object sender, EventArgs e)
{
this.listBoxRooms.Items.RemoveAt(this.listBoxRooms.SelectedIndex);
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
So i've got a Add and Remove button which work perfectly just need a solution to the edit button.
Thanks in advance
I'm guessing newRoomDisplayForm.value is a property or a public member inside the form. You just need to do something like this:
private void btnEdit_Click(object sender, EventArgs e)
{
if(listBoxRooms.SelectedIndex < 0) return;
var tmpValue = listBoxRooms.Items[listBoxRooms.SelectedIndex].ToString();
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.value = tmpValue;
newRoomDisplayForm.ShowDialog();
//TODO: inside "newRoomDisplayForm" set the value to the textbox
// ie.: myValueTextBox.Text = this.value;
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
// replace the selected item with the new value
listBoxRooms.Items[listBoxRooms.SelectedIndex] = newRoomDisplayForm.value;
}
}
Hope it helps!
You can simply remove the listitem in that specific position, create a new item and add it again. it's kind of replacement.

Winforms - Stop Dropdown of Combobox during DropDown event

I need to implement a ComboBox, which acts as follows:
When Click on the ComboBox, the client calling API method and updates the combobox items with the response.
My problem is, when I have 0 results - I want the ComboBox not to open (It has 0 items).
Is there a way to do that?
This is my current code:L
private void Combo_DropDown(object sender, EventArgs e)
{
// Private method which addes items to the combo, and returns false if no itmes were added
if (!AddItemsToComboBox())
{
// This is not working
Combo.DroppedDown = false;
}
}
You can make the DropDownHeight as small as possible (1). For example:
int iniHeight;
private void Form1_Load(object sender, EventArgs e)
{
iniHeight = Combo.DropDownHeight;
}
private void Combo_DropDown(object sender, EventArgs e)
{
Combo.DropDownHeight = (AddItemsToComboBox() ? iniHeight : 1);
}

C#: Saving and Loading a list of ComboBox Items to/from the app.config file

I am trying to save and load a list of combobox items to the .NET settings file (app.config).
With the following code, I want to load and save the data stored in an ArrayList cboCollection.
private void Form1_Load(object sender, EventArgs e)
{
if (Settings.Default.cboCollection != null)
this.comboBox1.Items.AddRange(Settings.Default.cboCollection.ToArray());
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
ArrayList arraylist = new ArrayList(this.comboBox1.Items);
Settings.Default.cboCollection = arraylist;
Settings.Default.Save();
}
When I open the project’s Properties pages, and select the Settings tab, I would like to store {"myItem1","myItem2","myItem3"} in an ArrayList cboCollection. Unfortunately, there is no such type System.Collections.ArrayList to select. What did I do wrong?
First of all, you didn't do anything. You took this code from here.
It doesn't work, because you didn't implement cboCollection object.
First you need a setting
then implement your class
[Serializable]
public MyClass
{
//something...
}
EDIT:
OK, forget about the class and just use System.Collections.Specialized.StringCollection. This way you can add items to the settings.
System.Collections.Specialized.StringCollection itemList = new System.Collections.Specialized.StringCollection();
fill your combobox items into itemList by looping each of them.
and then you can do as follows:
Settings.Default.cboCollection = itemList;

Categories

Resources