user3841581
user3841581

Reputation: 2747

Query to update the content of a cell using

I have a table with the following format:

column1   column2
   40       blue
   20       red

I have I would like to update the contain of my column based on a value entered a TextBox and a comboBox, for example if I select red from my comboBox and enter the value 30 in my TextBox , I would like my table to be updated as follow

column1   column2
   40       blue
   50       red

I thought of something like this:

update tablename set column1=....+TextBox.Text where column2=ComboBox.Text

My question how do I get the current content of that row? do I need a query to do that?

Upvotes: 0

Views: 177

Answers (3)

Danilo
Danilo

Reputation: 93

To add to the other responses, you should also be using parameterized query:

connection.Open();
SqlCommand command = new SqlCommand("UPDATE table SET column1 = column1 + @column1 WHERE column2 = @column2", connection);
SqlDataAdapter adp = new SqlDataAdapter();
adp.UpdateCommand = command;
adp.UpdateCommand.Parameters.Add(new SqlParameter("@column1", SqlDbType.Int));
adp.UpdateCommand.Parameters.Add(new SqlParameter("@column2", SqlDbType.VarChar));
adp.UpdateCommand.Parameters["@column1"].Value = Convert.ToInt32(TextBox.Text);
adp.UpdateCommand.Parameters["@column2"].Value = ComboBox.Text;
try
{
    adp.UpdateCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
    MessageBox.Show(ex.ToString());
}
finally
{
    connection.Close();
}

Upvotes: 1

PRABA
PRABA

Reputation: 460

directly pass the column name as shown below

update tablename set column1=column1+TextBox.Text where column2=ComboBox.Text

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269793

You are so close. You can just reference the column:

update tablename
    set column1 = column1 + TextBox.Text
    where column2 = ComboBox.Text;

I should note that you should not be constructing the query from user input. You should be parameterizing the query. There are two important reasons. The first is to prevent unexpected syntax errors. The second is to guard against SQL injection.

If you are just learning to program with SQL, then using parameters is doubly important. You don't want to start learning bad habits.

Upvotes: 2

Related Questions