Description
Insert Command is used to insert the data into the database.
Syntax
The following is the syntax for the select command.
[csharp]SqlCommand cmd=new SqlCommand("insert into table_name values("'"+textbox1value+"','"+textbox2value+"'",connection);[/csharp]
Examples
Follow the below steps to work with insert 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="btnInsert" runat="server" style="font-weight: 700" Text="Insert" Width="85px" />
</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 btnInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=hppavillion-pc;Initial Catalog=sample;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into employee values('"+txtName.Text+"','"+txtGender.Text+"','"+txtSalary.Text+"','"+txtDID.Text+"')",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}[/csharp]
- Run the application. Then you will get the following output.
Open the SQL server and check whether the insert operation done or not.