1

I have two combo boxes.One is a category combo box and the other is a subcategory combo Box. while selecting a category in combo-box its particular subcategory items should appear in the subcategory combo box.But we should not give the category and subcategory items in the code.it should fetch from the database.Please help me to write the code in NetBeans.

I wrote code like this, but it is not working

 try
    {
        Connection con=databaseConnection.createConnection();
        Statement stmt = con.createStatement();

     ResultSet rs;
    rs = stmt.executeQuery("select distinct category_name from category");
    while(rs.next())
    {
                String cat = rs.getString("category_name");
        combo_catgry.addItem(cat);
    }               

    }
    catch(Exception e)
    {
          JOptionPane.showMessageDialog(null,e); 
    } 
    try
    {
                   Connection con=databaseConnection.createConnection();
        Statement stmt = con.createStatement();

     ResultSet rs;
    rs = stmt.executeQuery("select subCategory from category where category_name ='"+catgry+"' ");
           // System.out.println(rs);
    while(rs.next())
    {
                String cat = rs.getString("subCategory");
        combo_sub.addItem(cat);
    }               

    }
    catch(Exception e)
    {
          JOptionPane.showMessageDialog(null,e); 
    }
kenz
  • 112
  • 12
  • 2
    Which part are you actually having problems with? Linking the combo-boxes? Retrieving data from the database? Apply results from the database to the combobox? – MadProgrammer Jul 03 '14 at 07:09
  • everything is about how to use DefaultComboBoxModel, or to switch between models, with prepared valuse, added to JComboBox at runtime, more that one time per week is asked similair question here, voting to close as too broad – mKorbel Jul 03 '14 at 07:16
  • 2
    Possible [duplicate](http://stackoverflow.com/q/3191837/230513). – trashgod Jul 03 '14 at 07:17
  • i posted the code now.i know how to retrive values from database to combobox. – kenz Jul 03 '14 at 07:29
  • but i dnt know how to code for getting the subcategory items in sub combobox while clicking the respective main item in the parent combobox – kenz Jul 03 '14 at 07:31

1 Answers1

3

The connection with database works correctly?

if yes, see this tutorial:

Here will explain step by step how to create dependent combobox.

That's how I learned, and works perfectly.

Try it and dont forget to give feedback

rpirez
  • 431
  • 2
  • 8
  • 20