Description
Update Command is used to update the data in the database.
Syntax
The following is the syntax for the update command.
[csharp]SqlCommand cmd=new SqlCommand("update table table_name set column_name=value where column_name=textbpoxvalue",connection);[/csharp]
Examples
Follow the below steps to work with update command.
- Create a new ASP.Net Web Application.
- Write the following code in the design form code behind(Example.aspx).
[html]<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
font-weight: bold;
text-align: right;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2">Name</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Gender</td>
<td>
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Salary</td>
<td>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Depart ID</td>
<td>
<asp:TextBox ID="txtDID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="btnUpdate" runat="server" style="font-weight: 700" Text="Update" Width="85px" OnClick="btnUpdate_Click" />
<br />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
[/html]
- Write the following C# code in the Code file(Example.aspx.cs)
[csharp]using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=hppavillion-pc;Initial Catalog=sample;Integrated Security=True");
SqlCommand cmd = new SqlCommand("update employee set salary='"+txtSalary.Text+"' and departmentid='"+txtDID.Text+"' where name='"+txtName.Text+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}[/csharp]
- Run the application. Then you will get the following output.