Save item in Combobox

Asked

Viewed 638 times

1

I have a combobox with some items added via form, by the property Items (Collection).

I wish I could leave it to the user to type new texts in this combobox, which in my case, is a combobox of product categories.

I created a code that adds the typed text to the combobox, but it does not remain there when the form is restarted, my question is, have how to add an item and make it remain in the items?

Note: There is no possibility for me to use database for this.

My code:

private void btnIncluirItens_Click(object sender, EventArgs e)
{
     // para inserir na última posição

    int cnt = cbCategoriaProduto.Items.Count;
    if (cbCategoriaProduto.Text != String.Empty)
    {
        cbCategoriaProduto.Items.Insert(cnt, cbCategoriaProduto.Text);

    }
    else
    {
        cbCategoriaProduto.Items.Insert(cnt, "Item " + cnt);
    }
    cbCategoriaProduto.Text = ""; //limpa a caixa de texto após a inclusão

}
  • You want to save the inserted ones permanently, either only in the session or only during the page access?

  • You want to keep the items on combobox only when your item addition form is closed or you want the items to remain when the entire application is closed?

1 answer

0

Make sure this code is sufficient for what you want.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace drawing {
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        ComboBox comboBox1 = new ComboBox();
        private void Form2_Load(object sender, EventArgs e)
        {

            comboBox1.Location = new Point(20, 60);
            comboBox1.Name = "comboBox1";
            comboBox1.Size = new Size(245, 25);

            comboBox1.Items.Add("A");
            comboBox1.Items.Add("B");
            comboBox1.Items.Add("C");
            comboBox1.Items.Add("D");
            comboBox1.Items.Add("Add");

            this.Controls.Add(comboBox1);
            comboBox1.SelectedValueChanged += OnComboBox1SelectionChanged;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        private void OnComboBox1SelectionChanged(object sender, EventArgs e)
        {
            ComboBox temp = (ComboBox)sender;
            if (temp.SelectedItem.ToString() == "Add")
            {
                temp.DropDownStyle = ComboBoxStyle.DropDown;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Add(comboBox1.Text);
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.