Make Class File Name Code.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
/// <summary>
/// Summary description for Code
/// </summary>
public class Code
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["yogesh"].ConnectionString);
public void GETCONNECTION()
{
con.Open();
}
public void CLOSECONNECTION()
{
con.Close();
}
public int INSERTDATA(SqlParameter[] pr, string query)
{
GETCONNECTION();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddRange(pr);
int i = cmd.ExecuteNonQuery();
CLOSECONNECTION();
return i;
}
public DataTable SELECTDATA(SqlParameter[] pr, string query)
{
GETCONNECTION();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cmd.Parameters.AddRange(pr);
DataTable dt = new DataTable();
ad.Fill(dt);
CLOSECONNECTION();
return dt;
}
}
Back Code To Insert Data
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
Code objcode = new Code();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
binddata();
}
}
public void binddata()
{
string content = string.Empty;
SqlParameter[] pr = new SqlParameter[0];
string query = "select * from employee";
DataTable dt = new DataTable();
dt = objcode.SELECTDATA(pr, query);
ddlbind.DataSource = dt;
ddlbind.DataTextField = "name";
ddlbind.DataValueField = "id";
ddlbind.DataBind();
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
int i = 0;
SqlParameter[] pr = new SqlParameter[2];
pr[0] = new SqlParameter();
pr[0].ParameterName = "@name";
pr[0].Value = txtname.Text;
pr[1] = new SqlParameter();
pr[1].ParameterName = "@address";
pr[1].Value = txtaddress.Text;
string query = "insert into employee(name,address) values(@name,@address)";
i = objcode.INSERTDATA(pr, query);
if (i > 0)
{
Response.Redirect(Request.RawUrl, false);
}
}
protected void ddlbind_SelectedIndexChanged(object sender, EventArgs e)
{
SqlParameter[] pr = new SqlParameter[1];
pr[0] = new SqlParameter();
pr[0].ParameterName = "@id";
pr[0].Value = Convert.ToInt32(ddlbind.SelectedItem.Value);
string query = "select * from employee where id=@id";
DataTable dt = new DataTable();
dt = objcode.SELECTDATA(pr, query);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}