I did some research and found this :
DataObject d = new DataObject();
d.SetData(DataFormats.Serializable, myObject);
d.SetData(DataFormats.Text, myObject.ToString());
myForm.DoDragDrop(d, DragDropEffects.Copy);
code snippet to drag drop in win forms.
And i tried implementing it like this (WPF) :
private void listView1_MouseMove(object sender, MouseEventArgs e)
{
try
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DataObject d = new DataObject();
d.SetData(DataFormats.Serializable, listView1.SelectedItem);
d.SetData(DataFormats.Text, listView1.SelectedItem.ToString());
DragDrop.DoDragDrop(listView1, d, DragDropEffects.Copy);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now I had thought when i drag dropped the ListViewItem into notepad it would probably copy the class name of the selected item (Because that's what listView1.SelectedItem.ToString()) is... But instead Notepad showed a picture of a cancel symbol while hovering, and copied nothing when i let go of the mouse button.
The over all goal of this is to change the class into a comma delimited string so when it copy pastes into notepad all of the data of the class will be in a nice format.
But if someone could help me just get the class name to copy i'm sure i could figure it out from there :o
So.... Yea.
bool alreadycopying = false;
private void listView1_MouseMove(object sender, MouseEventArgs e)
{
try
{
if (e.LeftButton == MouseButtonState.Released)
{
alreadycopying = false;
}
if (e.LeftButton == MouseButtonState.Pressed && alreadycopying == false)
{
alreadycopying = true;
System.IO.StreamWriter test = new System.IO.StreamWriter(#"C:\SuperSecretTestFile.txt");
test.WriteLine("Test");
test.Close();
List<String> testlist = new List<string>();
testlist.Add(#"C:\SuperSecretTestFile.txt");
DataObject d = new DataObject();
d.SetData(DataFormats.FileDrop, testlist.ToArray<string>());
DragDrop.DoDragDrop(listView1, d, DragDropEffects.All);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
After much bashing of poor notepad technology, c# comes out victorious <.<
Related
I am having a problem with a with a code that I used for my C# application. When I click on the browse button and select the file dialogue box opens twice.
private void txt_location_TextChanged(object sender, EventArgs e)
{
string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
folderPath = folderBrowserDialog1.SelectedPath;
}
}
private void Button21_Click(object sender, EventArgs e)
{
using(var fbd = new FolderBrowserDialog()) {
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) {
selectedPath = fbd.SelectedPath;
txt_location.Text = selectedPath;
}
}
}
private void bunifuThinButton21_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter file;
bool isvalid = ValidateInputs();
try {
file = new System.IO.StreamWriter(selectedPath + # "\dred.txt");
catch (Exception ex) {
MessageBox.Show("Please, Select valid Path..");
return;
}
try {
if (isvalid) {
WriteLines(file);
}
}
catch (Exception ex2) {
MessageBox.Show(ex2.Message);
}
finally {
file.Close();
}
}
}
Obviously, it is only meant to open once to enable me to read the selected file. This works, but only once I have selected the file twice.
Thanks in advance for your help.
You have FolderBrowserDialog being instantiated and shown on two different events:
txt_location_TextChanged
and
Button21_Click
You're having two popups because each one is firing once separately.
You should probably remove the event txt_location_TextChanged entirely unless you need it for another thing that isn't popping the FolderBrowserDialog again.
I am trying to make a text box in a WPF C# application populate a text box from a variable gathered from an external database using WCF and having little luck. Currently the text box states ScoreBoardClientTest.FeedServiceAgent instead of the value of agentsavailable. I was able to make this exact same code work in a console application when using this line of code inside of OnMessageReceived
console.writeline(e.cmsdata.skill.agentsavailable.tostring());
so I assumed I could do something similar here.
any help understanding where I'm going wrong would be great.
DisplayNumber is the name of the textbox.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
DisplayNumber.Text = data.ToString();
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
e.CmsData.Skill.AgentsAvailable.ToString();
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}
Edit
Changed:
DisplayNumber.Text =e.CmsData.Skill.AgentsAvailable.ToString();
to:
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }
This will handle multithreaded calls. You might have to add a using System.Threading statement for the DispatcherPriority enum
EndEdit
It is still unclear how to get from the data of Type FeedServiceAgent to a Skill.AgentsAvailable property in your Loaded event handler. We need more information on how to make that navigation. Is the assignment even necessary in the Loaded handler? I've marked the location in the code below.
I've also made what appears to be the necessary changes to the message handler method.
public void TextBlock_Loaded(object sender, EventArgs e)
{
using (var data = new FeedServiceAgent())
{
data.MessageReceived += OnMessageReceived;
data.Subscribe("92", 3);
//DisplayNumber.Text = data.ToString();
//Is this assignment even necessary?
DisplayNumber.Text = /*Still unclear what goes here because we don't know what how to get from `data` to `Skill`*/
}
}
public static void OnMessageReceived(object sender, MessageReceivedEventArgs e)
{
try
{
if (e == null)
return;
if (e.CmsData == null)
{
//e.CmsData.Skill.AgentsAvailable.ToString();
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { DisplayNumber.Text = e.CmsData.Skill.AgentsAvailable.ToString() ; }));
}
// if (!String.IsNullOrEmpty(e.Message))
// Console.WriteLine(e.Message);
}
catch (Exception ex)
{
// logger.Error(" Exception " + ex);
// throw ex;
}
}
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
I have this code that works fine when I call it from within the form, however, when I call the same from the Parent it runs through the code without results:
public void hideHelp()
{
//Check in db if panel1 is visible
SqlCeCommand checkHelp = new SqlCeCommand("Select Show_Help from Options where Opt_Id = 1", this.optionsTableAdapter.Connection);
if (this.optionsTableAdapter.Connection.State == ConnectionState.Closed)
{ this.optionsTableAdapter.Connection.Open(); }
try
{
bool showHelp = (bool)(checkHelp.ExecuteScalar());
this.panel1.Visible = showHelp;
this.Refresh();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
On Main form I have a toggle button with the following code:
private void tglHelp_Click(object sender, EventArgs e)
{
if (tglHelp.ToggleState.ToString() == "On")
{
HRDataSet.OptionsRow updateHelp = hRDataSet.Options.FindByOpt_Id(1);
try
{
updateHelp.Show_Help = true;
this.optionsTableAdapter.Update(this.hRDataSet);
Form activeChild = this.ActiveMdiChild;
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
tglHelp.Text = "Help Panel \nOFF";
}
Any ideas?
In this piece of code
if (activeChild.Name == "frmAddEmployees")
{
frmAddEmployees chForm = new frmAddEmployees();
chForm.MdiParent = this;
chForm.hideHelp();
}
you open another frmAddEmployees and add to the MDI, but you don't show it.
If your intent was to call the code in the current frmAddEmployees identified by the activeChild you should use something like this
if (activeChild.Name == "frmAddEmployees")
{
((frmAddEmployees)activeChild).hideHelp();
}
My question comes from a problem which I have right now. I have MainWindow, AuthenticateWindow, and AddEntryWindow which all are WinForms. In main window I have possibility to Authenticate and Add Entry into my main windows textbox. They can not add an entry until they authenticate (no problem with this). I need to add an entry to the text box which will update my main windows textbox. The problem if, how can I check if entry was added to my textbox?
I am trying to have a Save option from menu strip. I am getting an error whenever I am trying to save an empty file. How could I authenticate the saving process by Save button by having it first disabled, and enabled after entry was added?
I could always verify if if textbox had an entry but I want to have button disabled first, and enabled after entry was added. I do not have a privilege to do so as of right now.
Please ask questions if I am not clear enough.
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
if (txtDisplay.Text != string.Empty)
{
sfdSaveToLocation.ShowDialog();
}
}
MainWindow.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
// Prohibit editing.
txtDisplay.Enabled = false;
}
public string ChangeTextBox
{
get
{
return this.txtDisplay.Text;
}
set
{
this.txtDisplay.Text = value;
}
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
private void tsmiClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
sfdSaveToLocation.ShowDialog();
}
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string theFileName = sfdSaveToLocation.FileName;
EncryptDecrypt en = new EncryptDecrypt();
string encrypted = en.Encrypt(txtDisplay.Text,
storedAuth.UserName, storedAuth.Password);
MessageBox.Show(encrypted);
File.WriteAllText(theFileName, encrypted);
}
}
}
AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
string user, pass;
// Initializind ArrayList to store all data needed to be added or retrived.
private ArrayList addedEntry = new ArrayList();
// Initializing MainWindow form.
MainWindow mainWindow;
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
public AddEntryWindow(MainWindow viaParameter, string user, string pass)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
}
private void AddEntryWindow_Load(object sender, EventArgs e)
{ }
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex == -1)
{
MessageBox.Show("Please select entry type!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Each field must be filled for specified type.
// Here we are checking if all fields were filled.
else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
{
MessageBox.Show("Please fill all the fields!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int totalEntries = 0;
if(cmbType.SelectedIndex == 0)
addedEntry.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
else if(cmbType.SelectedIndex == 1)
addedEntry.Add(new AddWebSite(cmbType.Text,
txtUserName.Text, txtPassword.Text, txtURL.Text));
else if(cmbType.SelectedIndex == 2)
addedEntry.Add(new AddSerialCode(cmbType.Text,
txtSoftwareName.Text, txtSerialCode.Text));
StringBuilder stringBuilder = new StringBuilder();
foreach (var list in addedEntry)
{
if (list is AddPC)
{
totalEntries++;
AddPC tmp = (AddPC)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
totalEntries++;
AddWebSite tmp = (AddWebSite)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
totalEntries++;
AddSerialCode tmp = (AddSerialCode)list;
stringBuilder.Append(tmp.ToString());
}
}
mainWindow.ChangeTextBox = stringBuilder.ToString();
mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";
// Clearing all fields.
ClearFields();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing the Add Entry Window form.
this.Close();
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
// Deciding which data must be entered depending on
// what type is selected from combo box.
// PC
if (cmbType.SelectedIndex == 0)
{}
// Web Site
else if (cmbType.SelectedIndex == 1)
{}
// Serial Code
else if (cmbType.SelectedIndex == 2)
{}
}
private void ClearFields()
{
// Clearing all fields to the default state.
}
}
}
Regards.
It sounds like you probably just want to subscribe to the TextChanged event, which will be fired whenever the text in the textbox changes.
I can't say I really followed everything that you're doing, but I think you should be fine to just enable or disable your Save button within that event handler.
EDIT: It's not really clear where all your different components live, but you want something like:
// Put this after the InitializeComponent() call in the constructor.
txtDisplay.TextChanged += HandleTextBoxTextChanged;
...
private void HandleTextBoxTextChanged(object sender, EventArgs e)
{
bool gotText = txtDisplay.Text.Length > 0;
menuSaveButton.Enabled = gotText;
}
I'd also strongly advise you not to use ArrayList but to use the generic List<T> type. The non-generic collections should almost never be used in new code.