I have a TextBox, a Button, and a Combobox
When I click the Button, I want the text in Textbox to be added to the Combobox Items
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Add(textBox1.Text);
}
My form until open. This text shows in the Combobox, but when I close the Form and open it again the text is not longer shown in the Combobox.
I want to save the text to the Collection Items of the Combobox. I don't want to use a database.
As others have mentioned in the comments, you need to understand and decide where you wish to store your values.
For the purpose of my example, I have created a simple text file to store these values. The code reads from the file and adds each line as an item into the ComboBox.
private void Form1_Load(object sender, EventArgs e)
{
// Read items from file into a string array
string[] items = System.IO.File.ReadAllLines(#"D:\ComboBoxValues.txt");
// Add items to the comobobox when opening the form
comboBox1.Items.AddRange(items);
}
private void button1_Click(object sender, EventArgs e)
{
// Add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
// Put all existing comobo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
// Save the array of items to a text file (this will not append, it will re-write the file)
System.IO.File.WriteAllLines(#"D:\ComboBoxValues.txt", items);
}
This may not be the most elegant way of going about it, but from the point of providing you an understanding - this should be more than sufficient.
if you don't like to use File System, you can use Preferences(but it's not recommendable to use preference to memorize large values), check this link to see how create a new setting
private void Form1_Load(object sender, EventArgs e)
{
string[] strItems = Properties.Settings.Default.items.Split(", ");
for(int i = 0; i < strItems.length; i++) {
comboBox1.Items.Add(strItems[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
//add your new value to the combobox
comboBox1.Items.Add(textBox1.Text);
//put all existing combo box items into a string array
string[] items = comboBox1.Items.OfType<string>().ToArray();
for(int i = 0; i < items.length; i++) {
//I assumed you had an items key in your settings
if(i == items.length - 1) {
Properties.Settings.Default.items += value;
} else {
Properties.Settings.Default.items += value + ", ";
}
}
//then you should to save your settings
Properties.Settings.Default.Save();
}
Related
What I need:
I need a ComboBox and a CheckedListBox with exact same values.
I have a Button to add values and delete values.
Here is my Add Button:
private void button5_Click(object sender, EventArgs e)
{
checkedListBox1.Items.Add(comboBox1.Text);
comboBox1.Items.Add(comboBox1.Text);
comboBox1.Text = "";
}
and my Delete Button:
private void button6_Click(object sender, EventArgs e)
{
comboBox1.Items.Remove(comboBox1.SelectedItem);
}
I would like to be able to delete the entries in the CheckedListBox without having to select it first, I only need it to be selected into the comboBox1.
Since you're adding the same strings, you can use the IndexOf() method to get the index where the current string is located in your CheckedListBox and the RemoveAt() to remove it.
Verify that the ComboBox.SelectedItem is not null. You can use the GetItemText() method to get the string currently selected. If the SelectedItem is null, you get back a empty string.
private void button6_Click(object sender, EventArgs e)
{
string currentItem = comboBox1.GetItemText(comboBox1.SelectedItem);
if (!string.IsNullOrEmpty(currentItem))
{
checkedListBox1.Items.RemoveAt(checkedListBox1.Items.IndexOf(currentItem));
comboBox1.Items.Remove(comboBox1.SelectedItem);
}
}
Method2:
If the Items it the two controls are located at the same index, you can instead use the ComboBox.SelectedIndex to RemoveAt() both:
private void button6_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex >= 0)
{
checkedListBox1.Items.RemoveAt(comboBox1.SelectedIndex);
comboBox1.Items.RemoveAt(comboBox1.SelectedIndex);
}
}
I am making a small C# application where the user enters information. the information is stored in an object and the object is in turn stored in a list. The information is displayed to the user in a listview.
I want to make it so that when the user clicks on an item in the listview the index of that item is passed to the list which finds the object with the same index and gets its information. The information is then shown in the same textboxes that the user enters his or hers information in.
My problem is that i do not now what method to call when the user selects a row in the listview.
This is what i have:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 1)
{
index = listView1.FocusedItem.Index;
textBox1.Text = manager.FocusedContact(index).FirstName;
textBox2.Text = manager.FocusedContact(index).LastName;
textBox3.Text = manager.FocusedContact(index).Street;
textBox4.Text = manager.FocusedContact(index).City;
textBox5.Text = manager.FocusedContact(index).ZipCode;
}
}
i tried:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
textbox1.Text = "hi";
}
so i know that private void listView1_SelectedIndexChanged is the wrong method, or is there some option for the listview that i forgot to toggle on or off?
You should be able to retrieve the selected index like this:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
var index = listView1.SelectedIndex;
}
If the event is not firing at all, check that the event handler is registered correctly in the form's Designer.cs file. In your case, it should look like this:
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
I have combobox which is correctly populated with some field ID when button is clicked.
private void Button_Click(object sender, RoutedEventArgs e)
{
results.Items.Add(ID);
}
Now I want when I change some value to delete previous value (or values in case I have multiple values in combobox) but I am always getting exception (if some value is already selected in Combo Box)
I tried to add in that method on the top this:
results.Items.Clear();
and I tried this:
for (int i = 0; i < results.Items.Count; i++)
{
results.Items.RemoveAt(i);
i--;
}
But always getting exception:
System.ArgumentException: Value does not fall within the expected range.
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, Object[] rawData)
at MS.Internal.XcpImports.Collection_Add[T](PresentationFrameworkCollection'1 collection, Object value)
at System.Windows.PresentationFrameworkCollection'1.AddImpl(Object value)
at System.Windows.Controls.ItemCollection.AddImpl(Object value)
at System.Windows.Controls.ItemCollection.AddInternal(Object value)
at System.Windows.PresentationFrameworkCollection'1.Add(T value)
at SXPCreateIncident3.SilverlightControl1.results_SelectionChanged(Object sender, SelectionChangedEventArgs e)
at System.Windows.Controls.Primitives.Selector.OnSelectionChanged(SelectionChangedEventArg
If I don't have this part with Clear (Remove) then combobox has more elements on every button Click but I need to clear previous content when button is clicked.
Did you try unselecting all items before deleting:
results.SelectedIndex = -1;
results.Items.Clear();
And in case Clear would still cause some trouble, shouldn't your second method be:
for (int i = results.Items.Count - 1; i >= 0; i--)
{
results.Items.RemoveAt(i);
}
I'm not entirely sure how result.Items is bound to you Combobox but you might try to replace the unwanted item with a new one:
private void Button_Click(object sender, RoutedEventArgs e)
{
// itemToRemove should already be set
var index = result.Items.IndexOf(itemToRemove);
results.Items[index ] = ID;
}
To remove multiple items, do not use an iterator. Removing things from a collection while using an iterator messes the iterator up. You could however do this:
private void Button_Click(object sender, RoutedEventArgs e)
{
for(var i = 0; i < result.Items.Count; i++)
{
// itemsToRemove should be populated with the IDs you want to remove.
if(itemsToRemove.Contains(result.Items[i])
{
result.RemoveAt(i);
}
}
result.Items.Add(ID);
}
This loop won't get messed up because every time the expression i < result.Items.Count is evaluated and Count be one less then the previous Count when an ID has been removed.
EDIT
To clear the combobox and populate it with new items you'll have to provide a new ItemsSource for the combobox:
private void Button_Click(object sender, RoutedEventArgs e)
{
results.ItemsSource = null;
results.ItemsSource = new List<SomeType>(); // replace SomeType with the type of ID.
results.Items.Add(ID);
}
I have listview which is populated with list of data. Now I want to select desired row and on click button to recognize that item to delete from a collection.
Question is how to recognize selected row from the listview?
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = (MyData)....?
}
Thanks
This should works
private void buttonDelete_Click(object sender, EventArgs e)
{
//selected data is of custom type MyData
var selected = yourListView.SelectedItems.First();
}
To add to #Zaphod's answer and make a little more robust:
private void buttonDelete_Click(object sender, EventArgs e)
{
if (yourListView.SelectedItems.Any())
{
//selected data is of custom type MyData
var selected = yourListView.SelectedItems.First();
}
}
You could use .Count > 0 instead of .Any() and .SelectedItems[0] instead of .First(). Whatever you find more readable/maintainable.
Old School answer :) without any LINQ statements
if(yourListView.SelectedItems.Count > 0)
{
var item = yourListView.SelectedItems[0];
}
I don't think you have to use casting for a deleting operation, just remove all the selected indices like this:
private void buttonDelete_Click(object sender, EventArgs e){
for (int i = listView1.SelectedIndices.Count - 1; i >= 0; i--)
listView1.Items.RemoveAt(listView1.SelectedIndices[i]);
}
or more simply:
private void buttonDelete_Click(object sender, EventArgs e){
foreach(ListViewItem item in listView1.SelectedItems)
listView1.Items.Remove(item);
}
As you can see the item which is selected is of type ListViewItem, you can bind your data to this item via Text property (if the data is string) or Tag property. I don't understand what your CustomData is, is it a type inheriting ListViewItem?
YOu should do this
private void buttonDelete_Click(object sender, EventArgs e)
{
if (yourListView.SelectedItems.Any())
{
//selected data is of custom type MyData
var selected = (MyData)yourListView.SelectedItems[0];
YourCollection.Remove(selected);
}
}
i use an openFileDialog to read from a text file and print the values in a listbox and a saveFileDialog to save the changes in textfile.i wrote this code but it doesn't work.if a change the listbox with a textbox works fine.But i need to print and save the items into a listbox.any suggestions?
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label7.Text = openFileDialog1.FileName;
listBox1.Text = File.ReadAllText(label7.Text);
}
}
private void button5_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Text);
}
}
You need to add each line of the file as a listbox item. Then, to save, loop through each listbox item and write it as a new line.
You can use File.ReadAllLines and listBox1.Items.AddRange to add the items.
listBox1.Items.AddRange(File.ReadAllLines(openFileDialog1.FileName));
Since the Items property contains objects, not strings, you will need to manually loop over the items and write them individually... perhaps doing something like
StringBuilder sb = new StringBuilder();
foreach(object item in listBox1.Items) {
sb.AppendLine(item.ToString();
}
File.WriteAllText(saveFileDialog1.FileName, sb.ToString());
ListBox.Text represents only a selected part of the list box items.
A quote from MSDN docs:
When the value of this property is set to a string value, the ListBox searches for the item within the ListBox that matches the specified text and selects the item. You can also use this property to determine which items are currently selected in the ListBox
This should work :
using System.Linq;
...
string[] lines = File.ReadAllLines(fileName);
listBox.Items.AddRange(lines.ToArray<object>());