How to display value related to combobox in the textbox?

15

I'm doing a project in C # and SQL Server, and I need the item selected in the combo to display the corresponding values in a textbox .

Here are the codes I've tried:

        private void preencherCBDescricao()
        {

            SqlConnection con = new SqlConnection("Data Source=FS5;Initial Catalog=bdsi01;User ID=bdsi01;Password=*****");

            try
            {
                con.Open();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
            }
            String scom = "select titulo from Livros";
            SqlDataAdapter da = new SqlDataAdapter(scom, con);
            DataTable dtResultado = new DataTable();
            dtResultado.Clear();//o ponto mais importante (limpa a table antes de preenche-la)
            cbocompra.DataSource = null;
            da.Fill(dtResultado);
            cbocompra.DataSource = dtResultado;

            cbocompra.DisplayMember = "titulo";
            cbocompra.SelectedItem = "";
            cbocompra.Refresh(); //faz uma nova busca no BD para preencher os valores da cb de livros.


        }

        private void cbocompra_SelectedIndexChanged(object sender, EventArgs e)
        {
            string stg;
            stg = cbocompra.SelectedItem.ToString();

            SqlConnection con = new SqlConnection("Data Source=FS5;Initial Catalog=bdsi01;User ID=bdsi01;Password=*******");

            try
            {
                con.Open();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
            }

            String scom = "select * from Livros where titulo="+ stg;


            txtautor1.Text = cbocompra.SelectedItem.ToString();
            txtedit1.Text = cbocompra.SelectedItem.ToString();
            txtpreco.Text = cbocompra.SelectedItem.ToString();

        }

The question is, how can I save the values of my select in a list and after the item is selected I use the value of that item to search in the corresponding data list as the name Author, price to load my textbox with this information?

Type create a list and with it load my combobox , and when the user selects an item I load the textbox with the information of that item.

    
asked by anonymous 28.11.2015 / 19:39

4 answers

5

This process is quite simple.

In your example, assuming that the table does not have a primary key (ID) that uniquely identifies the records, the ComboBox control will have to receive the complete table to do all the work for you , indexing each record ( DataRow ) in your list to be accessed by the SelectedItem property.

Adjusting the code:

    private void preencherCBDescricao()
    {

        SqlConnection con = new SqlConnection("Data Source=FS5;Initial Catalog=bdsi01;User ID=bdsi01;Password=*****");

        try
        {           
            String scom = "select * from Livros";
            SqlDataAdapter da = new SqlDataAdapter(scom, con);
            DataTable dtResultado = new DataTable();
            da.Fill(dtResultado);

            //Limita aos itens da lista pendente
            cbocompra.DropDownStyle = ComboBoxStyle.DropDownList;
            cbocompra.DataSource = null;               
            cbocompra.DataSource = dtResultado;
            cbocompra.DisplayMember = "titulo";
            cbocompra.Text = "";//pode usar o .Text = "" ou o .SelectedIndex = -1 para limpar o item seleccionado.
        }
        catch (SqlException sqle)
        {
            MessageBox.Show("Falha ao efectuar a conexão. Erro: " + sqle);   
        }
    }

Next, in the event SelectedIndexChanged , you will not need to search the database again. The data is already in DataSouce of ComboBox . To get the selected row, we only use the SelectedItem property that is of type DataRowView . With this object, we can access each cell of the selected row, indicating the name or index of the column:

    private void cbocompra_SelectedIndexChanged(object sender, EventArgs e)
    {            
        //verifica se foi seleccionado um item na lista
        if (cbocompra.SelectedIndex != -1)
        {

             //Podemos obter o linha seleccionada com a propriedade SeletedItem                 
             DataRowView drw = ((DataRowView)cbocompra.SelectedItem);
             txtautor1.Text =  drw["titulo"].ToString();
             txtedit1.Text =  drw["editora"].ToString();
             txtpreco.Text =  drw["preco"].ToString();
         }
         else
         {
             txtautor1.Text = "";
             txtedit1.Text = "";
             txtpreco.Text = "";
         }
    }
    
26.05.2016 / 18:32
4

Well if I understood in an Index of the comboBox has more than one information: Author, Edit, Price ..  If you want to remove these values you should get the index selected by the client / user and specify in SelectedIndex to then use SelectedItem , but since you have 3 information you should get this value to a string and then use the foreach to split using Split.

Your code could look like this:

string DadosSelecionados = null;
            MyCombo.SelectedIndex = 0; //index que foi selecionado, EX:0
            DadosSelecionados = MyCombo.SelectedItem.ToString();

                                       //0           //1           //2
            DadosSelecionados = "O mundo Increvel, Editora Nova, R$325,50";//digamos que foram esses os dados selecionados
            string[] Dados = DadosSelecionados.Split(',');
                                           //0 1 2 << 3
            string[] MyDados = new string[3];
            int i = 0;
            foreach(string s in Dados)
            {
                MyDados[i] = s.ToString();
                i++; //mesma coisa de i+=1! não confunda com ++i;
            }

            //seta os dados no seus textbox
            TXTNome.Text = MyDados[0].ToString();
            TXTEditora.Text = MyDados[1].ToString();
            TXTpreco.Text = MyDados[2].ToString(); 

It has errors due to being done in the same hand .. but you just need to understand the concept ..  :)

    
04.12.2015 / 18:12
4

I suppose there are multiple items, so it is better to work with a List and for each item to create an object.

Class example for items:

private class Item
{
    public string Autor {get; set;}
    public string Editora {get; set;}
    public string Preco {get; set;}

    public Item(string Autor, string Editora, string Preco)
    {
        this.Autor = Autor;
        this.Editora = Editora;
        this.Preco = Preco;
    }
}

Create the list for the items

List<Item> lista = new List<Item>();

The string data as colleague Vyctor Junior is made and places the item in the list:

string DadosSelecionados = "As Loucas Aventuras de James West, Editora Nova, R$325,50";
string[] itens = DadosSelecionados.Split(new string[] { ", "});
Item it = new Item(itens[0], itens[1], itens[2]);
lista.Add(it);

The ComboBox accepts enumerations, so simply pass the list to the DataSource property. For it to know what will be displayed for each item in the list, it writes the name of the class property or struct Item in the ComboBox property DisplayMember . Suppose it is Autor :

cbocompra.DataSource = lista;
cbocompra.DisplayMember = "Autor";

In the event that the user changes the item, the SelectedItem property will have the item selected (in the form of an object). Then just cast and fill in the TextBox.

Item item= (Item)cbocompra.SelectedItem;
txtautor1.Text = item.Autor;
txtedit1.Text = item.Editora;
txtpreco.Text = item.Preco;

That's the easiest way I know it. I made the hand so they may have syntax errors. I hope I have helped.

    
06.03.2016 / 23:31
4

With visual studio this is done automatically with the help of ADO.NET. All you have to do is create a DataSource with the fields and tables you want, and using "click and drag" you put the ComboBox of the table and the TextBox of the columns inside your Form.

Look at the image below:

Explaining: When you create a table instance a DataSet is created to access the database, a TableAdapter for the interface accesses the data, and a BindingSource to select the rows.

The BindingSource that controls the selected and visible data, that is, when you select an item in the instance (ComboBox) that references the table, BindingSource will swap all the contents of the instances referenced by the columns (TextBox).

Remembering that it is better to create the table reference (ComboBox) first, because the TextBox will assimilate the DataAdapter and the BindingSource automatically, otherwise several DataAdapters and BindingSources will be created

    
06.04.2016 / 06:43