Tips & Tricks: Drag and Drop code from Visual Studio Toolbox

Introduction:

In this article i will explain how to drag and drop common code from Visual Studio Toolbox.

When we are writing code in our projects, we need to write few line of code again and again. In that case what we will do? We will copy that code and paste wherever it is required or we will re-write that code. Even if we copy that common code into a file/notepad then also we need to open that file, copy, and paste that code. To avoid this we have one nice feature in visual studio. We can move our common code to visual studio toolbox. Let's see this with simple example.

Example:

Assume we are writing SqlConnection related code to fetch data from database in many places. For this i'm writing SqlConnection related code as shown below:

namespace VSTipsAndTricks
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection sqlConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = sqlConnection;
            // SqlCommand related properties are assigned here.

            sqlConnection.Open();
            // Some logic goes here
            sqlConnection.Close();
        }
    }
}

Select the common code as shown below:

Drag and drop selected code into toolbox area then you will see something with text file icon as shown below:

Now remove the code from Main(...) method as shown below:

Hover your mouse on Text: file icon in toolbox, it will shows the common code in tooltip as shown below: 

Now drag and drop common code from toolbox into Main(...) method as show below:

Move common coed file into new Tab:

If if you want to move this common code into seperate tab then right click (r + click) on General Tab then select Add Tab option.

Give some name to the new tab like Common Code.

Then move the common code from General Tab to Common Code Tab.

Rename Common Code file:

Right click on (r + click) on common code text file in Common Code tab then select Rename Item option.

Give name like Make SqlConnection as shown below:

This way you can drag and drop your common code into toolbox and viceversa.

That's it. I hope you enjoyed this article. We will add more articles on "Tips & Tricks" in the coming days.

  • Created
    Apr 09, 2015
  • Updated
    Dec 29, 2019
  • Views
    653