protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string strConnString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnString))
{
string strQuery = "SELECT * FROM Products";
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
protected void Add(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string CategoryId = (control.FindControl("txtCatid") as TextBox).Text;
string Product_Name = (control.FindControl("txtProduName") as TextBox).Text;
string product_id = (control.FindControl("txtproductid") as TextBox).Text;
string Product_price = (control.FindControl("txtprodctprice") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [products] VALUES(@CategoryId, @Product_Name,@productid, @Product_price)";
cmd.Parameters.AddWithValue("@CategoryId",CategoryId);
cmd.Parameters.AddWithValue("@Product_Name",Product_Name);
cmd.Parameters.AddWithValue("@productid", product_id);
cmd.Parameters.AddWithValue("@Product_price",Product_price);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}