How to display combobox-related value in the textbox?

Asked

Viewed 6,318 times

15

I am 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.

Follow 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 list the corresponding data as the author name, price to load mine textbox with that information ?

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

  • 2

    What is the behavior of this code? Displays error? Executes, but the values do not appear? What would be?

  • What is your main problem in this code?

  • @Ciganomorrisonmendez, I made an issue in the question , I believe this is what she needed...

  • I’m having some difficulty to make the data that are linked to combobox appear in the textbox, for example: I have a table books in the database and in my combobox appear the names of the books registered and I wanted the author of that book selected in the combobox to appear in the textbox

  • @Marconciliosouza The correct would be to edit itself, but approving the edition we can reopen.

  • @Gypsy omorrisonmendez, perfect

  • I want help to solve my problem, not to edit my question. Sorry if I was rude, but in the textbox appears datareader gridview instead of the requested data.

  • @Nataliasouza, The point is that it was not clear your question, See what you need explain if I understood, in the first method your preencherCBDescricao you carry your cbocompra with the result of your select and your method cbocompra_SelectedIndexChanged You want to carry your own TextBox according to what you have in the cbocompra for this you have to keep a list of the select you did in the first method or go again to the bank to fetch this information, ... if this is it edits your question explaining better...

  • @Nataliasouza, I think we don’t always express ourselves in the best way, I think the well-meaning editions are welcome. Back to your problem, it’s okay to upload a project to Git with the complete solution to your problem ? The answers below are satisfactory ?

Show 4 more comments

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 control Combobox will need to receive the full table to do all the work for you, indexing each record (DataRow) on your list to be accessed by the property SelectedItem.

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);   
        }
    }

Coming up next at the event SelectedIndexChanged, the database will not need to be searched again. The data is already in the DataSouce of Combobox. To get the selected line, we use only the property SelectedItem who’s kind DataRowView. With this object, we can access each cell of the selected row, indicating the column name or index:

    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 = "";
         }
    }

4

I’m guessing multiple items, so you better work with one List and for each item 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 list for items

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

Get the string data as the colleague Vyctor Junior made and puts the item on 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);

Combobox accepts enumerations, so just pass the list to the property DataSource. To let him know what will appear on each item in the list, type the name of the class or struct property Item on the property of Combobox DisplayMember. Suppose it is Autor:

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

In the event when the user changes the item to property SelectedItem will have the item selected (in Object form). Then just cast and fill the Textbox.

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

This is the easiest way I know how to do it. I made the hand, so there may be syntax errors. I hope I helped.

4

Good if I understood in an Index of combobox has more than one information: Author, Edit, Price.. If you want to remove these values you must obtain the index selected by the client/user and specify in Selectedindex and then use the Selecteditem, but since you have 3 information you must get this value for a string and then use foreach to separate 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 be done in the same hand.. but you just need to understand the concept.. :)

4

With visual studio this is done automatically with the help of ADO.NET. Just create a Datasource with the desired fields and tables, and using the "click and drag" you place the Table Combobox and the columns Textbox inside your Form.

Note the image below:

Exemplo de DataSource no Visual Studio 2015

Explaining: When you create a table instance a Dataset is created to access the database, a Tableadapter for the interface to access the data and a Bindingsource to select the lines.

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 exchange all contents of the instances referenced by the columns (Textbox).

Remembering that it is better to create the table reference (Combobox) first, so the Textbox will assimilate the Dataadapter and Bindingsource automatically, otherwise several Dataadapters and Bindingsources will be created

Browser other questions tagged

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