Problems loading a text file into RichText (C#) - c#

I'm having trouble loading a file into a RichText control.
First, there are no events in the designer to accomodate drag/drop, so I put these handlers in the form initialization.
Second, the DragEnter() event does not seem to identify text files properly, so dropping is disabled in the RichText (it works fine for a ListBox).
Third, if I get the RT to load the file, it displays an icon/filename inside the RT text area. I cant find any references to this behavior, and can't turn it off.
This code does NOT work:
public Form1()
{
InitializeComponent();
RT.AllowDrop = true;
RT.DragEnter += new System.Windows.Forms.DragEventHandler(RT_DragEnter);
RT.DragDrop += new System.Windows.Forms.DragEventHandler(RT_DragDrop);
}
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// when a text file is dragged to this control, GetDataPresent() returns FALSE.
// this seems to be regardless of the file extension. File is ASCII text only.
// this code DOES work if the underlying control is a ListBox.
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
// when the file is loaded, the RT also displays an icon for the file,
// with the filename, inside the text area ... ?
RT.LoadFile(filenames[0],RichTextBoxStreamType.PlainText);
}
}
In order to get the RT to load a dropped file properly, I use a timer to load the RT outside of the
DragDrop() event:
public string FileToLoad;
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// allow anything:
//if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
//else
//e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
FileToLoad = filenames[0];
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
if (FileToLoad.Length > 0)
{
RT.LoadFile(FileToLoad, RichTextBoxStreamType.PlainText);
FileToLoad = "";
}
}
The latter has the RichText loading the file properly, but this seems like a long way around the block to get LoadFile() to work as expected. Am I doing something wrong?

Related

C# Streamwriter enabling by button

I would like to create application in which I could create file, write something into it by button clicking and then close this file by clicking another button. The problem is that when I've declared Streamwrtier object within one button I couldn't invoke file close method from within second button because I've got such error: the name 'file' does not exist in the current context. When I initiate Streamwriter outside the button method problem dissapeares but then file is being created before I will click button. Do you know how could I overcome this issue?
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
StreamWriter file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
file.Close();
}
Here's the basic fix:
private StreamWriter file = null;
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
if (file == null)
file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
if (file is object)
file.Close();
}
But really, it's poor practice in most cases to hold the file open. You generally want something more like this, which handles opening and closing the necessary streams all in one go, and only keeps the file open for the minimum necessary duration:
public void button1_Click(object sender, EventArgs e)
{
File.AppendAllText("test.txt", value.ToString());
}
And since we always close the file right away, the second button isn't needed at all.

How to make Drag&Drop work?

I have a textbox on a winform in Visual Studio. I want to drag&drop files on it. This is what I have done:
public LangMerge()
{ InitializeComponent();
this.AllowDrop = true;
tbxFilepath.AllowDrop = true;
tbxFilepath.DragDrop += new DragEventHandler(tbxFilepath_DragDrop);
tbxFilepath.DragEnter += new DragEventHandler(tbxFilepath_DragEnter);
}
void tbxFilepath_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) tbxFilepath.Text=(file);
}
void tbxFilepath_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
Neither the drag effect nor the receiving of the file does not work. No error messages or warnings. What could be the problem?
UPDATE: I inserted breakpoints into the event handler methods and the code doesn't get into them in the first place, no matter what I do with the cursor.
You have set AllowDrop=true; and handled DragDrop() and DragEnter() events, however for winforms application you need to also handle TextBox.DragOver() event :
Something like this :
private void textBoxFile_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}

Pass file path from file in listbox to dataconext C#

I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}

How to drag & drop only one file on form window

I have one windows application in c#, i want to add drag & drop facility in this application, after adding this facility it takes multiple files, so I want to take only one file at a time, how to do this?
read the code below and try applying it to your situation
public Form1()
{
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += Form1_DragEnter;
this.DragDrop += Form1_DragDrop;
}
void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e)
{
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files.Length == 1)
{
// do what you want
}
else
{
// show error
}
}

Dragging files into rich textbox to read text in file

I'm having a problem with dragging and dropping files onto a richTextBox, every time I drag a text file onto it, it turns into a picture of the text file with its name under it. Double click the file and it opens up using the system default application (ie notepad for text files, etc). basically its making shortcuts in the richTextBox, when i want it to read the text in the file.
Based on this code, the text from the file should extract into richTextBox1
class DragDropRichTextBox : RichTextBox
{
public DragDropRichTextBox()
{
this.AllowDrop = true;
this.DragDrop += new DragEventHandler(DragDropRichTextBox_DragDrop);
}
private void DragDropRichTextBox_DragDrop(object sender, DragEventArgs e)
{
string[] fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
if (fileNames != null)
{
foreach (string name in fileNames)
{
try
{
this.AppendText(File.ReadAllText(name) + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Any ideas on how to make this work?
you need to check the draged object before you are reading into file. try below code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
richTextBox1.DragDrop += new DragEventHandler(richTextBox1_DragDrop);
richTextBox1.AllowDrop = true;
}
void richTextBox1_DragDrop(object sender, DragEventArgs e)
{
object filename = e.Data.GetData("FileDrop");
if (filename != null)
{
var list = filename as string[];
if (list != null && !string.IsNullOrWhiteSpace(list[0]))
{
richTextBox1.Clear();
richTextBox1.LoadFile(list[0], RichTextBoxStreamType.PlainText);
}
}
}
use this to bind DragEnter and DragDrop event for RichTextBox in Designer.cs
this.richTextBox1.AllowDrop = true; this.richTextBox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.textBox1_DragDrop); this.richTextBox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.textBox1_DragEnter);
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
try
{
Array a = (Array)e.Data.GetData(DataFormats.FileDrop);
if (a != null)
{
string s = a.GetValue(0).ToString();
this.Activate();
OpenFile(s);
}
}
catch (Exception ex)
{
MessageBox.Show("Error in DragDrop function: " + ex.Message);
}
}
private void OpenFile(string sFile)
{
try
{
StreamReader StreamReader1 = new StreamReader(sFile);
richTextBox1.Text = StreamReader1.ReadToEnd();
StreamReader1.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error loading from file");
}
}
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
For starters, Kazankoph is incorrect when he tells you there is no "AllowDrop."
He made this statement in 2013, and AllowDrop has existed since NET Framework was released on 13 February 2002. You'll find this at the link below.
In fact, it is code you can use in Vb.net as well. As for the "EnableAutoDragDrop" if you go to your form design and "right-click" on the RichTextBox and go to "Properties", you'll find that "EnableAutoDragDrop" is normally set at "False" and you have to set the properties manually to "True." I took a screenshot of my code just to prove that "AllowDrop" does exist. I am placing the code I use to Drag & Drop in the event you find it useful. Be sure to EnableAutoDragDrop in properties as explained above.
Granted this is a C# question, he's backing for my statement of AllowDrop for C#, with an example:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox.allowdrop?view=windowsdesktop-6.0
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
AllowDrop = True
AddHandler RichTextBox1.DragEnter, New DragEventHandler(AddressOf RichTextBox1_DragEnter)
AddHandler RichTextBox1.DragDrop, New DragEventHandler(AddressOf RichTextBox1_DragEnter)
End Sub
'Drag Load RichTextBox1
Private Sub RichTextBox1_DragDrop(sender As Object, e As DragEventArgs)
' Loads the file into the control.
RichTextBox1.LoadFile(CType(e.Data.GetData(Text), String), RichTextBoxStreamType.RichText)
End Sub
'Drag Effects RichTextBox1
Private Sub RichTextBox1_DragEnter(sender As Object, e As DragEventArgs)
If e.Data.GetDataPresent(DataFormats.Text) Then
CType(e, DragEventArgs).Effect = DragDropEffects.Copy
Else
CType(e, DragEventArgs).Effect = DragDropEffects.None
End If
End Sub

Categories