Wednesday 16 September 2015

Efficiently Inserting Data into Multiple Tables Using Primary and Foreign Keys

Efficiently Inserting Data into Multiple Tables Using Primary and Foreign Keys.
this is a very short online invoice genration project i hope u enjoy this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;

namespace InvoiceDemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string strConnString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
        SqlCommand cmd;
        int count;
        SqlDataAdapter da = new SqlDataAdapter();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                autogenerateid();
                SetInitialRow();
            }
        }
        private void autogenerateid()
        {
            SqlConnection con = new SqlConnection(strConnString);
            string str = "Select Count(*) from tblInvoiceDetails";
            cmd = new SqlCommand(str, con);
            con.Open();
            cmd.ExecuteNonQuery();

            count = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
            txt_invoiceno.Text = count.ToString();
            txt_invoiceno.Enabled = false;
            con.Close();
            ViewState["invoiceid"] = txt_invoiceno.Text;

        }

        protected void ddl_companyname_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void SetInitialRow()
        {
            int quant = 0;
            int pri = 0;
            DataTable dt = new DataTable();
            DataRow dr = null;

            dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));

            dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));
            dt.Columns.Add(new DataColumn("Quantity", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(string)));
            dt.Columns.Add(new DataColumn("invoiceid", typeof(int)));
            dr = dt.NewRow();
            dr["RowNumber"] = 1;

            dr["ProductName"] = string.Empty;
            dr["Description"] = string.Empty;
            dr["Quantity"] = string.Empty;
            dr["Price"] = string.Empty;
            dr["invoiceid"] = Convert.ToInt32(ViewState["invoiceid"]);
            dt.Rows.Add(dr);


            //Store the DataTable in ViewState
            ViewState["CurrentTable"] = dt;
            gridviewproduct.DataSource = dt;
            gridviewproduct.DataBind();
        }

        protected void btn_save_Click(object sender, EventArgs e)
        {
            int lastid;
            SqlConnection con = new SqlConnection(strConnString);
            SqlCommand cmd = new SqlCommand(strConnString, con);

            cmd.CommandText = "sp_insertinvoice";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();


            //cmd.Parameters
            cmd.Parameters.AddWithValue("@invoice_date", txtDate.Text);
            cmd.Parameters.AddWithValue("@Firm_name", txt_frmname.Text.Trim());
            cmd.Parameters.AddWithValue("@Regis_id", txt_regno.Text.Trim());
            cmd.Parameters.Add("@idcategory", SqlDbType.Int).Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            lastid = Convert.ToInt32(cmd.Parameters["@idcategory"].Value.ToString());
            con.Close();

            insertProductdetails();
            BulkInsertToDatabase();
            txtDate.Text = string.Empty;
            txt_frmname.Text = string.Empty;
            txt_regno.Text = string.Empty;

        }
        private void BulkInsertToDatabase()
        {
            //int lastinvoiceid = Convert.ToInt32(ViewState["id"]);
            DataTable dtProductDetails = (DataTable)ViewState["CurrentTable1"];
            //int index = Convert.ToInt32(dtProductDetails.Rows[4]);
            SqlConnection con = new SqlConnection(strConnString);
            SqlBulkCopy objBulk = new SqlBulkCopy(con);
            con.Open();
            objBulk.DestinationTableName = "tbl_ProductDetails";
            objBulk.ColumnMappings.Add("ProductName", "Product_Name");
            objBulk.ColumnMappings.Add("Description", "Product_Description");
            objBulk.ColumnMappings.Add("Quantity", "Qty");
            objBulk.ColumnMappings.Add("Price", "Price");
            objBulk.ColumnMappings.Add("invoiceid", "Invoice_id");
            objBulk.WriteToServer(dtProductDetails);
            con.Close();
        }


        private void insertProductdetails()
        {
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtcurrentTable = new DataTable();// = (DataTable)ViewState["CurrentTable"];
                DataRow dtCurrentRow = null;

                if (gridviewproduct.Rows.Count > 0)
                {

                    dtcurrentTable.Columns.Add(new DataColumn("ProductName", typeof(string)));
                    dtcurrentTable.Columns.Add(new DataColumn("Description", typeof(string)));
                    dtcurrentTable.Columns.Add(new DataColumn("Quantity", typeof(int)));
                    dtcurrentTable.Columns.Add(new DataColumn("Price", typeof(int)));
                    dtcurrentTable.Columns.Add(new DataColumn("invoiceid", typeof(int)));


                    for (int i = 0; i < gridviewproduct.Rows.Count; i++)
                    {
                        dtCurrentRow = dtcurrentTable.NewRow();

                        dtCurrentRow["ProductName"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_productname")).Text;
                        dtCurrentRow["Description"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_description")).Text;
                        dtCurrentRow["Quantity"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_qty")).Text;
                        dtCurrentRow["Price"] = ((TextBox)gridviewproduct.Rows[i].FindControl("grd_txt_price")).Text;
                        dtCurrentRow["Invoiceid"] = Convert.ToInt32(ViewState["invoiceid"]);




                        dtcurrentTable.Rows.Add(dtCurrentRow);
                    }


                    ViewState["CurrentTable1"] = dtcurrentTable;
                }



            }

        }


        protected void ButtonAdd_Click1(object sender, EventArgs e)
        {
            AddNewRowToGrid();

        }
        private void AddNewRowToGrid()
        {
            int rowIndex = 0;

            if (ViewState["CurrentTable"] != null)
            {

                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                   {
                       //extract the TextBox values
                       // TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productid");
                       TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                       TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                       TextBox box3 = ((TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty"));
                       TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");

                       drCurrentRow = dtCurrentTable.NewRow();
                       drCurrentRow["RowNumber"] = i + 1;

                       // dtCurrentTable.Rows[i - 1]["ProductId"] = box1.Text;
                       dtCurrentTable.Rows[i - 1]["ProductName"] = box1.Text;
                       dtCurrentTable.Rows[i - 1]["Description"] = box2.Text;
                       dtCurrentTable.Rows[i - 1]["Quantity"] = box3.Text;
                       dtCurrentTable.Rows[i - 1]["Price"] = box4.Text;
                       dtCurrentTable.Rows[i - 1]["invoiceid"] = Convert.ToInt32(ViewState["id"]);

                       rowIndex++;
                   }
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    gridviewproduct.DataSource = dtCurrentTable;
                    gridviewproduct.DataBind();
                }
            }
            else
            {
                Response.Write("ViewState is null");
            }

            //Set Previous Data on Postbacks
            SetPreviousData();
        }
        private void SetPreviousData()
        {
            int rowIndex = 0;
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productid");
                        TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                        TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                        TextBox box3 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty");
                        TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");

                        // box1.Text = dt.Rows[i]["ProductId"].ToString();
                        box1.Text = dt.Rows[i]["ProductName"].ToString();
                        box2.Text = dt.Rows[i]["Description"].ToString();
                        box3.Text = dt.Rows[i]["Quantity"].ToString();
                        box4.Text = dt.Rows[i]["Price"].ToString();
                        rowIndex++;
                    }
                }
            }
        }

        protected void btnupload_Click(object sender, EventArgs e)
        {
            if (fileupload1.HasFile)
            {
                string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                fileupload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + filename);
                lblstatus.Text = "Success";
            }
            else
            {
                lblstatus.Text = "Unsuccessful";
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Button clickedButton = sender as Button;
            GridViewRow row = (GridViewRow)clickedButton.Parent.Parent;
            int rowID = Convert.ToInt16(row.RowIndex);

            gridviewproduct.DeleteRow(rowID);
        }

        protected void gridviewproduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            setRowData();
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dt = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                int rowIndex = Convert.ToInt32(e.RowIndex);
                if (dt.Rows.Count > 1)
                {
                    dt.Rows.Remove(dt.Rows[rowIndex]);
                    drCurrentRow = dt.NewRow();
                    ViewState["CurrentTable"] = dt;
                    gridviewproduct.DataSource = dt;
                    gridviewproduct.DataBind();
                    for (int i = 0; i < gridviewproduct.Rows.Count - 1; i++)
                    {
                        gridviewproduct.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    }
                    SetPreviousData();
                }
            }
        }
        private void setRowData()
        {
            int rowIndex = 0;
            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        TextBox box1 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[1].FindControl("grd_txt_productname");
                        TextBox box2 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[2].FindControl("grd_txt_description");
                        TextBox box3 = ((TextBox)gridviewproduct.Rows[rowIndex].Cells[3].FindControl("grd_txt_qty"));
                        TextBox box4 = (TextBox)gridviewproduct.Rows[rowIndex].Cells[4].FindControl("grd_txt_price");
                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["RowNumber"] = i + 1;

                        dtCurrentTable.Rows[i-1]["ProductName"] = box1.Text;
                        dtCurrentTable.Rows[i-1]["Description"] = box2.Text;
                        dtCurrentTable.Rows[i-1]["Quantity"] = box3.Text;
                        dtCurrentTable.Rows[i-1]["Price"] = box4.Text;

                        rowIndex++;
                    }
                    ViewState["CurrentTable"] = dtCurrentTable;


                }
            }
            else
            {
                lbl_msg.Text = "View State is null";
            }
        }

    }



We have use sql Bulk copy here to insert more than one row in database using single statement 

No comments:

Post a Comment

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow