Asheer Butt
Asheer Butt

Reputation: 11

How to use combobox text in update query

Please tell me how to take a combobox text as a column name.

Here is my code :

string query = "update teacher set '"+comboBox1.Text+"' = '" + textBox2.Text + "' where teacherid='" + textBox1.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, conn);
sda.SelectCommand.ExecuteNonQuery();

I want to use text of combobox as a set column name in update query it gives error

Upvotes: 0

Views: 523

Answers (4)

uzman
uzman

Reputation: 21

    JButton btnNewButton_13 = new JButton("Update");
    btnNewButton_13.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //////////////////
            
            try {
                if(textField_4.getText().equals("")||textField_1.getText().equals("")||textField_2.getText().equals("")||comboBoxRoomType.getSelectedItem().equals("")||textField_3.getText().equals("")){
                    JOptionPane.showMessageDialog(null, "Please fill the form and check the details");
                }else {
                Connection con = DBConnection.connect();
                
                String query="Update Locations set RoomName='"+textField_2.getText()+"',BuildingName='"+textField_1.getText()+"' ,RoomType='"+comboBoxRoomType.getSelectedItem().toString()+"'  where LID='"+textField_4.getText()+"' ";
                PreparedStatement pst=con.prepareStatement(query);
                pst.executeUpdate();
                JOptionPane.showMessageDialog(null, "Data Updated");
                
                
                pst.close();
                }
                
            }
            catch(Exception q) {
                q.printStackTrace();
            }

Upvotes: 0

Bijeesh Raghavan
Bijeesh Raghavan

Reputation: 69

Try the following code:

string query = "update teacher set '"+comboBox1.SelectedItem.ToString(+"' = '" + textBox2.Text + "' where teacherid='" + textBox1.Text + "'"; 

SqlDataAdapter sda = new SqlDataAdapter(query, conn);
sda.SelectCommand.ExecuteNonQuery();

Upvotes: 2

Sabah Shariq
Sabah Shariq

Reputation: 45

You could try using the following code.

string abc = comboBox1.SelectedItem.ToString();
MessageBox.Show(abc);

So your code should like this:

string query = "update teacher set '" + comboBox1.SelectedItem.ToString() + "' = '" + textBox2.Text + "' where teacherid='" + textBox1.Text + "'";

Also you could look into following DOCS article for more info on Combobox item selection

ComboBox.SelectedItem Property

Upvotes: 0

Akshay Phadke
Akshay Phadke

Reputation: 81

Just try this

comboBox1.selectedItem.Text 

Upvotes: 0

Related Questions