Shivani Varshney
Shivani Varshney

Reputation: 11

How to update records in SQL Server database through asp.net?

I'm writing this code in asp.net but still it's not updating record in a SQL Server database:

SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();

while (dr.Read())
    SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " '  where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+        "' ", conn);

Upvotes: 0

Views: 634

Answers (3)

RiyajKhan
RiyajKhan

Reputation: 53

You are Missing ExecuteNonQuery Method Write Below code

SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();

while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " '  where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+        "' ", conn);
cmd3.executeNonQuery();

Upvotes: 1

pilak
pilak

Reputation: 39

Proper way to use ado.net:

var newId = count + 1;
var roomType = typeRadioButtonList1.SelectedItem.ToString();

using (var connection = new SqlConnection("your db connection string here"))
{
        var query = "UPDATE [roomdetail] SET [rid] = @rid WHERE [rid] = 0 AND roomtype = @roomType";

        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@rid", newId);
        command.Parameters.AddWithValue("@roomType", roomType);

        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            //handle exception
        }
}

Upvotes: 2

Avi K.
Avi K.

Reputation: 1802

Assuming the connection is already opened, in your while loop you are missing the following statement:

cmd3.ExecuteNonQuery();

You have to execute the command in order for the database to be updated.

Upvotes: 0

Related Questions