How to Bind sql data to Datagridview in Windows application using C#.Net


Bind data to Datagridview in window application is same as bind data to Gridview in web application.
First Create one windows forms application give the name as Form.cs. In that form drag Datagridview from toolbox  and double click on form then form_load event will be opend in that write the following code:

private void Form1_Load(object sender, EventArgs e)
        {
            //This connection string is used to connect to database
            String strConnection = "Data Source=naresh;Initial Catalog=EMPDB;Integrated Security=True";
            //Establish SQL Connection
            SqlConnection con = new SqlConnection(strConnection);
            //Open database connection to connect to SQL Server
            con.Open();
            //Data table is used to bind the resultant data
            DataSet dsempdetails = new DataSet ();
            // Create a new data adapter based on the specified query.
            SqlDataAdapter da = new SqlDataAdapter("Select * from UserMaster", con);
            //SQl command builder is used to get data from database based on query
            SqlCommandBuilder cmd = new SqlCommandBuilder(da);
            //Fill data table
            da.Fill(dsempdetails,"EmpTable");
            //assigning data table to Datagridview
            dataGridView1.DataSource = dsempdetails .Tables[0];

            //Resize the Datagridview column to fit the gridview columns with data in datagridview
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            con.Close();
        }

After bind data to DataGridView then the output will be shown like this:


What are the new features in Visual Studio 11 Beta version:


The following points shows about the features of Visual Studio 11 Beta version:
  1.      It support for TFS and unit testing tools.
  2.      It Included ASP.NET MVC 3 and ASP.NET MVC 4 Beta
  3.      It supports HTML 5
  4.      With VS11 Beta, you can create a unit test project into an existing web solution. Unit test explorer is    fully functional to run unit tests and view results.
  5.      It provides  Page Inspector, new CSS editor, new JavaScript editor.
  6.      It includes New HTML editor functionalities.
  7.      With VS11 Beta, you can also use profiling with IIS Express.
  8.      The default database for Visual Studio 11 is SQL Server 2012 Express LocalDB.
  9.      Visual Studio 11 Express Beta allows the project and website to target .NET framework 4.5 or 4.0. Developers should feel more freedom to choose the targeting framework with this release.


Insert or Upload document into database and retrieving, downloading with Saving option using C# and asp.net


First Create a table with the name Document in database which requires to saving  and  retrieving from database.
For Save, Just am saving NameOftheDocument,Document,DocumentType and Filename.
For that Design textbox and fileupload control and one Save button using asp.net
Then  in Save button click event write the following code:
    protected void btnSave_Click(object sender, EventArgs e)
        {
            string NameOftheDocument = txtNameOfDocument.Text;
            byte[] imgbyte = new byte[0];
            string DocType = string.Empty;
            string FileName = string.Empty;
            if (AsyFUCreateDocument.HasFile)
            {
                int length = AsyFUCreateDocument.PostedFile.ContentLength;
                imgbyte = new byte[length];
                HttpPostedFile img = AsyFUCreateDocument.PostedFile;
                img.InputStream.Read(imgbyte, 0, length);
                DocType = AsyFUCreateDocument.PostedFile.ContentType;
                FileName = AsyFUCreateDocument.PostedFile.FileName;
             }

//Pass these fields are as parameters to database and Save it.

 // Create SQL Connection

            SqlConnection con = new SqlConnection("data Source=ADMIN;initial catalog=databasename; user id=Sa; password=123");
            // Create SQL Command
             SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Document(NameOftheDocument,Document,DocumentType , Filename)" + " VALUES (@NameOftheDocument,@Document,@DocumentType ,@ Filename)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            SqlParameter NameOftheDocument       new SqlParameter("@NameOftheDocument",SqlDbType.VarChar, 50);
           NameOftheDocument.Value = NameOftheDocument.ToString();
            cmd.Parameters.Add(NameOftheDocument);

           
            SqlParameter Documentnew SqlParameter("@Document ",SqlDbType.Image, imgbyte.Length);
           Document.Value = imgbyte;
            cmd.Parameters.Add(Document);
            SqlParameter DocumentType new SqlParameter("@DocumentType ",SqlDbType.VarChar, 50);
           DocumentType.Value = DocumentType.ToString();
            cmd.Parameters.Add(DocumentType);

            SqlParameter Filenamenew SqlParameter("@Filename ",SqlDbType.VarChar, 50);
           Filename.Value = Filename.ToString();
            cmd.Parameters.Add(Filename);

            con.Open();

            int result = cmd.ExecuteNonQuery();

            con.Close();

            if (result > 0)

                lbmsg.Text = "Document Uploaded";



Then retrieve data from document table by using data Adapter and fill it into dataset.


After that:


The following article is showing about download a document file form dataset table[0] means one datatable.

For that first you have to retrieve data from database and Fill it into One Datatable.
Then write the following methods where ever you requires.


public string GetMimeTypeByFileName(string sFileName)
     {
         string sMime = "application/octet-stream";

         string sExtension = System.IO.Path.GetExtension(sFileName);
         if (!string.IsNullOrEmpty(sExtension))
         {
             sExtension = sExtension.Replace(".", "");
             sExtension = sExtension.ToLower();

             if (sExtension == "xls" || sExtension == "xlsx")
             {
                 sMime = "application/ms-excel";
             }
             else if (sExtension == "doc" || sExtension == "docx")
             {
                 sMime = "application/msword";
             }
             else if (sExtension == "ppt" || sExtension == "pptx")
             {
                 sMime = "application/ms-powerpoint";
             }
             else if (sExtension == "pdf")
             {
                 sMime = "application/pdf";
             }
             else if (sExtension == "rtf")
             {
                 sMime = "application/rtf";
             }
             else if (sExtension == "zip")
             {
                 sMime = "application/zip";
             }
             else if (sExtension == "mp3")
             {
                 sMime = "audio/mpeg";
             }
             else if (sExtension == "bmp")
             {
                 sMime = "image/bmp";
             }
             else if (sExtension == "gif")
             {
                 sMime = "image/gif";
             }
             else if (sExtension == "jpg" || sExtension == "jpeg")
             {
                 sMime = "image/jpeg";
             }
             else if (sExtension == "png")
             {
                 sMime = "image/png";
             }
             else if (sExtension == "tiff" || sExtension == "tif")
             {
                 sMime = "image/tiff";
             }
             else if (sExtension == "txt")
             {
                 sMime = "text/plain";
             }
         }

         return sMime;
     }



The following DataTable dt, you can take from your dataset tables[0] then write the method and

Call the following method in Download button click:
     public void download(DataTable dt)
     {
         Byte[] bytes = (Byte[])dt.Rows[0]["Image"];
         string filename = dt.Rows[0]["FileName"].ToString();
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.Buffer = false;
      HttpContext.Current.Response.Charset = "";
      HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
      HttpContext.Current.Response.ContentType = GetMimeTypeByFileName(filename);

      HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename="+filename.Replace(" ", "_"));
      HttpContext.Current.Response.BinaryWrite(bytes);
  
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.End();

     }

After clicking Download button then you will get Open with file and Save file Options.