Saturday, October 20, 2012

C# WIN FORM-SEPARATE DATABASE CONNECTION CLASS TO SQL

I have seen most of people try to connect with database with creating database connection again and again..OOp concept we can use to prevent that problem. Use following class for call any place to connect with data base..


public class dbCon
{
    string strconnection="Data Source=Rajitha-PC\\SQLexpress;Initial Catalog=POS;User ID=etutor_master_admin;Password=123;Integrated Security=True";
 
    SqlConnection sqlcon = new SqlConnection();
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();

    public void connect()
    {      
        sqlcon = new SqlConnection(strconnection);
        sqlcon.Open();
    }
    public void disconnect()
    {
        if (sqlcon.State == ConnectionState.Open)
        {
            sqlcon.Close();
            sqlcon.Dispose();
        }
    }
    public DataTable ReadData(string query)
    {
        try
        {
            connect();
            sqlcmd = new SqlCommand(query, sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            dt = new DataTable();
            da.Fill(dt);          
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            disconnect();
        }
        return dt;
    }
    public void QryCommand(string query)
    {
        try
        {
            connect();
            sqlcmd = new SqlCommand(query, sqlcon);
            sqlcmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            disconnect();
        }
    }



 Thats it..

Now Yo can call these from your coding windows


dbCon db = new dbCon();
DataTable dt=new DataTable();
dt = db.ReadData("select * from emp");
DataGridView1.DataSource=dt;


Wednesday, July 11, 2012

Insert and Retreive Image to SQL databse using C# form

I searched to insert image into sql database from c# form..TRied for a long days..Every efforts was use less...
But I NEVER GIVEUP....worked hard and found the solution baby...It is like dat...I m explain it..







This picture box will only displays the image you are going to save in your database providing some id in the textbox (I used this to just recall the image from database) once an image is loaded on the clicking event of Store button we are going to insert that image with provided ID into the database and the combo box will load itself with all available IDs in our database. By selecting an id we and clicking Retrieve the respective image will be shown in the second picture box.
So, now right click on your form and select view code.


Here declare a global string


string imagename;


a data adapter


SqlDataAdapter empadap1;


and a dataset

DataSet dset;


you will also require to use System.IO and System.Data.SqlClient

using System.IO;
 
using System.Data.SqlClient;



now we need to create a method to insert our image into the database and second method to retrieve all images. I named the method inserting my image into the database as update() and to retrieve my images I named my method as connection(). Now update() uses filestream to convert the image into binary data since image datatype in SQL Server 2005 use to store binary data in its image datatype. While connection() simply convert that binary data to an image using identical technique for us. Code for both the methods is:

private void updatedata()
    {
 
        //use filestream object to read the image.
 
        //read to the full length of image to a byte array.
 
        //add this byte as an oracle parameter and insert it into database.
 
        try
        {
 
            //proceed only when the image has a valid path
 
            if (imagename != "")
            {
 
                FileStream fs;
 
                fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read);
 
                //a byte array to read the image
 
                byte[] picbyte = new byte[fs.Length];
 
                fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
 
                fs.Close();
 
                //open the database using odp.net and insert the data
 
                string connstr = @"Data Source=.;Initial Catalog=TestImage;
                Persist Security Info=True;User ID=sa";
 
                SqlConnection conn = new SqlConnection(connstr);
 
                conn.Open();
 
                string query;
 
                query = "insert into test_table(id_image,pic) values(" + 
                textBox1.Text + "," + " @pic)";
 
                SqlParameter picparameter = new SqlParameter();
 
                picparameter.SqlDbType = SqlDbType.Image;
 
                picparameter.ParameterName = "pic";
 
                picparameter.Value = picbyte;
 
                SqlCommand cmd = new SqlCommand(query, conn);
 
                cmd.Parameters.Add(picparameter);
 
                cmd.ExecuteNonQuery();
 
                MessageBox.Show("Image Added");
 
                cmd.Dispose();
 
                conn.Close();
 
                conn.Dispose();
 
                Connection();
 
            }
 
        }
 
        catch (Exception ex)
        {
 
            MessageBox.Show(ex.Message);
 
        }
 
    }
 
    //----------------------------------------
 
    private void Connection()
    {
 
        //connect to the database and table
 
        //selecting all the columns
 
        //adding the name column alone to the combobox
 
        try
        {
 
            string connstr = @"Data Source=.;Initial Catalog=TestImage;

            Persist Security Info=True;User ID=sa";
 
            SqlConnection conn = new SqlConnection(connstr);
 
            conn.Open();
 
            empadap1 = new SqlDataAdapter();
 
            empadap1.SelectCommand = new SqlCommand("SELECT * FROM test_table"

            , conn);
 
            dset = new DataSet("dset");
 
            empadap1.Fill(dset);
 
            DataTable dtable;
 
            dtable = dset.Tables[0];
 
            comboBox1.Items.Clear();
 
            foreach (DataRow drow in dtable.Rows)
            {
 
                comboBox1.Items.Add(drow[0].ToString());
 
                comboBox1.SelectedIndex = 0;
 
            }
 
        }
 
        catch (Exception ex)
        {
 
            MessageBox.Show(ex.Message);
 
        }
 
    }


now double click the Load button and write the code lines:

try
        {
 
            FileDialog fldlg = new OpenFileDialog();
 
            //specify your own initial directory
 
            fldlg.InitialDirectory = @":D\";
 
            //this will allow only those file extensions to be added
 
            fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
 
            if (fldlg.ShowDialog() == DialogResult.OK)
            {
 
                imagename = fldlg.FileName;
 
                Bitmap newimg = new Bitmap(imagename);
 
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
 
                pictureBox1.Image = (Image)newimg;
 
            }
 
            fldlg = null;
 
        }
 
        catch (System.ArgumentException ae)
        {
 
            imagename = " ";
 
            MessageBox.Show(ae.Message.ToString());
 
        }
 
        catch (Exception ex)
        {
 
            MessageBox.Show(ex.Message.ToString());
 
        }
Now double click Store button and call the update () method to insert selected image into the database.


updatedata();

the update method itself calls connection() therefore combo box will be filled with IDs of images exits in database, one can use the connection method in anyway the person likes.
Finally double click Retrieve button and write


DataTable dataTable = dset.Tables[0];
 
        //if there is an already an image in picturebox, then delete it
 
        if (pictureBox2.Image != null)
        {
 
            pictureBox2.Image.Dispose();
 
        }
 
        //using filestream object write the column as bytes and store 
        it as an image
 
        FileStream FS1 = new FileStream("image.jpg", FileMode.Create);
 
        foreach (DataRow dataRow in dataTable.Rows)
        {
 
            if (dataRow[0].ToString() == comboBox1.SelectedItem.ToString())
            {
 
                byte[] blob = (byte[])dataRow[1];
 
                FS1.Write(blob, 0, blob.Length);
 
                FS1.Close();
 
                FS1 = null;
 
                pictureBox2.Image = Image.FromFile("image.jpg");
 
                pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
 
                pictureBox2.Refresh();
 
            }
 
        }



Thats my way...Try it and tell about it...If you dont like dont doooo...scooby duby dooooooooo


Visit Srilanka...Its my beautiful country


CraZy Programmer


Rajitha Anuradha
rajithasomarathna@gmail.com





C# open a new form, and close a form...

I tried to close the current form and I start a new form..In this process you can meet following problems


1) this.close()-will close all forms
2) this.hide() -will hide current form..but its opened


I found the way to overcome from this issue..Its really simple..


Write a method like this way



public static void ThreadProc()
{
    Application.Run(new newForm());
}


Then when you click to open a new form,dat button click event like as below

private void button1_Click(object sender, EventArgs e)
{
    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
    t.Start();
}

This worked for me....

Happy coding...No where Like Srilanka...Visit here...meet meeeee

Rajitha Anuradha(Phd In craZy Programming)
rajithasomarathna@gmail.com

C U zoon......

Friday, June 15, 2012

Use google to overcome from errors

When you are coding there may be different errors may arise. Some can solve easily with our knowledge. But sometimes errors are arising seriously...I have face so many this kind of problems..There's a simple way to overcome from it.It is Google the error .Then it will display the reason..easy solution..try it!!!

Use stored procedures in SQL Operations to have better results

I tried to insert image to a sql database and retrieve it in windows application.I tried the both ways.Command type with text and Command type with stored procedures.I saw some easy in stored procedures. It can re use easilly.Try it ..Actually its easy than Commanding in the application..We have to create stored procedures in sql......Try it and Happy coding..

Thursday, May 10, 2012

Cannot ALTER TABLE in SQL2008/SQL2008 R2


If you want to modify a table property through the UI which requires a table recreation, then you need to change the following options in Management Studio:
Tools ->Options-> Designers -> Table and Database Designers -> uncheck the option "Prevent saving changes that require table re-creation"
It worked for me.
Welcome to all ..This is an short blog.IT will help to you to overcome from programming problems...Here we goooooo!!!!!!!!!!!!!!!!!!