Wednesday 22 August 2012

c# tutorial

USING LINQ TO SQL INSERT INTO DATABASE










Saving to the database using LINQToSQL

Step1:
 Create the database in MSSQL Management studio

Step2:
Connect to the MSSQL Database from Visual Studio

Step3:
 Design the interface to take name,Mat no and picture

Step4:
 Add LINQ to Sql classes from Visual Studio

Step5:
Write The codes like this



CODES TO INSERT INTO THE DATABASE:

 customerDataContext db; 
        CustomerTB cust;
        private void btnsubmit_Click(object sender, EventArgs e)
        {
            db = new customerDataContext();
            cust = new CustomerTB()
            {
                ID = txtboxmatno.Text,
                name = txtboxname.Text,
                photo=pix
            };

            db.CustomerTBs.InsertOnSubmit(cust);
            db.SubmitChanges();
            txtboxmatno.Clear();
            txtboxname.Clear();
        }



CODES TO BROWSE FOR THE PICTURE:

  OpenFileDialog openfile;
        string path;
        byte[] pix;
        FileStream fs;
        private void btnbrowse_Click(object sender, EventArgs e)
        {
            openfile = new OpenFileDialog();
            openfile.ShowDialog();
            path = openfile.FileName;
            pictureBoxsubmit.Image = Image.FromFile(path);
            pictureBoxsubmit.SizeMode = PictureBoxSizeMode.StretchImage;
            fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            pix=new byte[fs.Length];
            fs.Read(pix, 0, Convert.ToInt32(fs.Length));

        }



CODES TO RETRIVE NAME AND PICTURE:

  ImageConverter imageconvert;
        private void btnretrieve_Click(object sender, EventArgs e)
        {
            byte[] retrevedPix = null;
            imageconvert = new ImageConverter();
            db = new customerDataContext();
            cust = new CustomerTB();
            cust = (from c in db.CustomerTBs where c.ID == txtboxretrivematno.Text select c).Single<CustomerTB>();
            txtboxretrievename.Text = cust.name;
            retrevedPix = cust.photo.ToArray();
           pictureBoxretrive.Image=(Image)imageconvert.ConvertFrom(retrevedPix);
            pictureBoxretrive.SizeMode=PictureBoxSizeMode.StretchImage;
        }








No comments:

Post a Comment