Drag and Drop Text Files on Windows Form

This post explains how we can directly drag and drop text files in Windows Form. so whenever you drag and drop the text files it will be open in the Application. Let's Create a new new C# Windows Form Application project and name it as Drag and Drop.

Right Click on the Windows Form and select "Properties".



In the Properties window under behaviour set AllowDrop to True.


Then drag and drop Richtextbox to the windows form and  create a form events for dragenter and DragandDrop the paste the following code.

Source Code

 private void Form1_DragDrop_1(object sender, DragEventArgs e)
        {
            try
            {
                string[] sData = (string[])e.Data.GetData(DataFormats.FileDrop, false);
                //MessageBox.Show(sData[0].ToString());
                StreamReader strReader = new StreamReader(sData[0]);
                textBox1.Text = strReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception:" + ex.ToString());
            }
        }

        private void Form1_DragEnter_1(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;

        }
Download Source Code

No comments :

Post a Comment