How to Insert Values into Database in Asp.net using C#

How to Insert Values into Database in Asp.net using C#

Insert Values into Database in Asp.net using C#

Here is How Our Aspx file will look in Design View –

Insert Values into Database in Asp.net using C#

Please Note : Respected “IDs” of Form Fields.

Use Following Namespaces in your C# code :
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.Text;
using System.Data.SqlClient;
using System.Configuration;

Code your button click like this :

On Button Click An Insert Statement will be executed

Note : In our case Table Columns are country, city and area and their values will be fetched from DropDownlist1 , txtCity and TextCountry respectively.

protected void btnCity_Click(object sender, EventArgs e)
{
try
{
string Insert = “insert Into Test_Country(country,city,area) values(‘” + DropDownList1.SelectedValue + “‘,'” + txtCity.Text + “‘, ‘” + TextCountry.Text + “‘)”;
SqlCommand com = new SqlCommand(Insert, con);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
txtCity.Text = ” “;
Response.Redirect(“http://slidescope.com”);
if (i > 0)
{
lblMsg1.Text = “<h1>Data Posted</h1> <table border=’1’><tr><td></td></tr></table> “;
}
}
catch (SqlException ex)
{
lblMsg1.Text = ex.Message;
}
}

Social Share

Leave a Reply

Your email address will not be published. Required fields are marked *