Sunday, May 20, 2018

How to insert data into database using asp.net C#


Database:
1.First of all create a database in SQL server, whatever you name it, like: "MyDatabase".
2.Then go to the created database i.e MyDatabase, right click on the "table" folder and click create new table.
3.Now add the columns:
a) The first column should be Primary key, give the name Employe_ID and set the datatype int.
-Primary key is a unique value for each row of data. It cannot contain null values.
Make sure that the Key column's datatype is int and then setting identity manually, as image shows:
enter image description here
b)Now Right-click on the column and select Set Primary Key.
c)Now add another column and name it "Employe_Name", set Datatype as varchar(100).
d)Add the last column the "Employe_Email", set Datatype as varchar(100).
3. Now press crt+s for saving table, give the name "Employee" and save it.
OR you can also run following query:
Create table  Employee
(
  Employee_ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
 Employee_Name varchar(100),
 Employe_Email varchar(100)
)

Now we are done with database.
Visual Studio:
1.In visual studio create new website,Add a webform and open aspx page.
After creating the project now first of all create the connetion string in web-config file (already present in web project).
 Add the following code undner the <configuration> tag:
 <connectionStrings>
    <add name="ConnectionString"
    connectionString="data source=.\SQLEXPRESS;initial catalogue=MyDatabase;Integrated Security=SSPI";providerName="System.Data.SqlClient" />
  </connectionStrings>
2.Now add the two textbox from the toolbox on left side.
or just past the following code in aspx page.
Employee Name:
<br>
<asp:TextBox id="txtEmployeeName"  runat="server" />
<br>
Employee Email:
<br>  
<asp:TextBox id="txtEmployeeEmail" runat="server" />
<br>
3. Now we also need a button so drag it from toolbox and drop under the textboxes in webform.
4. Now we need a event for performing the operation so double click on the created button .you will lend on open codebehind file of webform.
5.Now add the following namespace:
a). System.Data.SqlClient
b). System.Configuration
6. Now put the following code in the button event:
var cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

var query = "insert into Emmployee(Employee_Name, Employee_Email) values(@Name,@Email)";

using (SqlConnection cnn = new SqlConnection(cs))
{
    using (SqlCommand cmd = new SqlCommand(query, cnn))
    {
        cmd.Parameters.AddWithValue("@Name",txtEmployeeName.Text);
        cmd.Parameters.AddWithValue("@Email",txtEmployeeEmail.Text);
        cnn.Open();
        cmd.ExecuteNonQuery();
    }
}

If you have any question or you want to me write a tutorial on some topic, please post it in the comment.
Thank You.