Make TextBox text disappear after mouse click - c#

I'm new to C# so this is my first task essentially, I'm hoping to make a simple login page.
I would like the text to disappear from the textbox once it has been clicked, here's what I have tried so far;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
bool hasBeenClicked = false;
private void textBox1_Focus(object sender, EventArgs e)
{
TextBox box = sender as TextBox;
box.Text = string.Empty;
hasBeenClicked = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
This is from a similar post on here, It doesn't seem to work for me.
Here is something else I have tried;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Text = "";
}
I understand it may be a silly mistake, I'm learning.
Any helps is massively appreciated :)
I'm using Winforms

Try using the event MouseClick on the TextBox:
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
this.textBox1.Text = "";
}
In your screenshot, you are missing a reference. Click into the textbox events and add it like so:

Both of which should probably work but you've got to link the event to the function. You can either do this in the Designer or in code. For the Mouse click variant to work and link the event in code you can add the following in the constructor:
public Form1()
{
InitializeComponent();
this.MouseClick += textbox1_MouseClick;
}

Add Event Handler
You have not linked the given methods with the event, as you can see 0 refereces for both functions. You can add a mouse Click event as:
textBox1.Click += new System.EventHandler(textbox1_Mouseclick);
Similarly, you have to add event if you want to do with the focus event.

Related

Drag an item in listview to a form

I have two forms; one of them is containing listview, and another one is just a form.
I want to make a thing :
If I drag an item in listview to a Form, a messagebox would be pop up.
and the message would be text of the item.
However I don't know why 'SelectedItem' is null. When I trace the SelectedItem, it was null.
I found I have to use MouseDown and DragDrop events, but I have no idea how to use.
First one is the listview's code :
rListCtrl.MouseDown += rListCtrl_MouseDown;
rListCtrl.DragDrop += rListCtrl_DragDrop;
private void rListCtrl_MouseDown(object sender, MouseEventArgs e)
{
StringBuilder sb = new STringBuilder();
sb.Append(radListView1.SelectedItem.ToString());
testName = sb.ToString();
}
private void rListCtrl_DragDrop(object sender, DragEventArgs e){
{
MessageBox.Show(testName);
}
radListView1 is the name of listview.
The reason why SelectedItem is null, is that the Item only gets selected when you actually perform a click, not a mere MouseDown.
You can, however, use the IndexFromPoint method to get the Item the mouse had been placed on when the MouseDown Event was evoked:
private void radListView1_MouseDown(object sender, MouseEventArgs e)
{
int index = radListView1.IndexFromPoint(e.Location);
radListView1.SelectedIndex = index;
testName = radListView1.Items[index].ToString();
}
private void rListCtrl_DragDrop(object sender, DragEventArgs e){
{
MessageBox.Show(testName);
}
Form1:
public partial class Form1 : Form
{
Form2 f = new Form2();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
f.Show();
}
private void Form1_MouseEnter(object sender, EventArgs e)
{
if(f.data!= string.Empty)
{
MessageBox.Show(f.data);
f.data = string.Empty;
}
}
}
Form2:
public partial class Form2 : Form
{
public string data = string.Empty;
public Form2()
{
InitializeComponent();
listView1.ItemDrag += doDaragItem;
}
private void doDaragItem(Object sender, ItemDragEventArgs e)
{
data = e.Item.ToString();
}
}
Ron,
RadListView from the Telerik UI from WinForms suite handles the whole drag and drop operation by its ListViewDragDropService. Its PreviewDragOver event allows you to control on what targets the item(s) being dragged can be dropped on. The PreviewDragDrop event allows you to get a handle on all the aspects of the drag and drop operation, the source (drag) list view, the destination (target) control, as well as the item being dragged. Additional information is available in the following help article: https://docs.telerik.com/devtools/winforms/controls/listview/drag-and-drop/listviewdragdropservice
https://docs.telerik.com/devtools/winforms/controls/listview/drag-and-drop/drag-and-drop-using-raddragdropservice
You can also combine the RadDragDropService and OLE drag-and-drop functionality: https://docs.telerik.com/devtools/winforms/controls/listview/drag-and-drop/combining-raddragdropservice-and-ole-drag-and-drop
As to the specific code snippet, indeed, if you don't have a selected item in RadListView, the code in the MouseDown event won't extract the item's text. You need to get the element under the mouse and set the item as selected:
private void radListView1_MouseDown(object sender, MouseEventArgs e)
{
SimpleListViewVisualItem elementUnderMouse = this.radListView1.ElementTree.GetElementAtPoint(e.Location) as SimpleListViewVisualItem;
if (elementUnderMouse != null)
{
this.radListView1.SelectedItem = elementUnderMouse.Data ;
}
StringBuilder sb = new StringBuilder();
sb.Append(radListView1.SelectedItem.Text.ToString());
{
testName = sb.ToString();
}
MessageBox.Show(testName);
}
I hope this information helps.

How to get Usercontrol object 'X' from X's Button(i.e. Button inside the X) onclick event

Hello guys i am working on a Windows Form application in .Net C#.
Now i have a User control with a button inside it.
however i had to write the on-click handler in the main form rather than inside the user-control itself.
Now i want to know if there is anyway i can get the User-control object in the Button's on-click Handler. Since i had to make use of them few more times in the same form. I want to know which User-control's Button was click.
User Control
Button
Thank You :)
Here's an example of the UserControl raising a Custom Event that passes out the source UserControl that the Button was clicked on:
SomeUserControl:
public partial class SomeUserControl : UserControl
{
public event ButtonPressedDelegate ButtonPressed;
public delegate void ButtonPressedDelegate(SomeUserControl sender);
public SomeUserControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (ButtonPressed != null)
{
ButtonPressed(this); // pass the UserControl out as the parameter
}
}
}
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
someUserControl1.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
someUserControl2.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
someUserControl3.ButtonPressed += new SomeUserControl.ButtonPressedDelegate(SomeUserControl_ButtonPressed);
}
void SomeUserControl_ButtonPressed(SomeUserControl sender)
{
// do something with "sender":
sender.BackColor = Color.Red;
}
}
You can use event:
public delegate void ButtonClicked();
public ButtonClicked OnButtonClicked;
You can then subscribe the event anywhere, for instance, in your MainForm, you have a user control called demo;
demo.OnButtonClicked +=()
{
// put your actions here.
}
Just walk the .Parent() chain until you find a Control that is the same Type as your UserControl. In the example below, the UserControl is of Type SomeUserControl:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
someUserControl1.button1.Click += new EventHandler(button1_Click);
someUserControl2.button1.Click += new EventHandler(button1_Click);
someUserControl3.button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
Control uc = btn.Parent;
while (uc != null && !(uc is SomeUserControl))
{
uc = uc.Parent;
}
uc.BackColor = Color.Red;
MessageBox.Show(uc.Name);
}
}

Raising an event when button clicked and subscribing it to eventhandler in another class?

I have a form.cs which contains a button and a texbtox, and also a class which handles the event raised when the button is clicked.
basically, when the button is clicked, it should raise an event and the eventHandler in Print class should print text to TboxPrint in the form
this is how my code looks like:
//Declare the delegate
public delegate void EventHandler(object sender, EventArgs e);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//event
public event EventHandler Print;
//Event caller, protected to prevent calling from other classes
protected virtual void OnPrint(System.EventArgs e)
{
if (Print != null) Print(this, e);
}
//raising event
public bool print_action(object value)
{
OnPrint(EventArgs.Empty);
return true;
}
public void BtnPrint_Click(object sender, EventArgs e)
{
PrintClass p = new PrintClass();
Form1 s = new Form1();
s.Print += p.printEventHandler;
print_action(true);
}
}
and the class with method handling the event is:
class PrintClass
{
public void printEventHandler(object sender, EventArgs e)
{
string text = "Print Event occured";
}
}
Apparently nothing is raised.. i believe the way i m raising the event or subscribing to the event handler is wrong. and how i pass the text in eventhandler back to form?
any help is appreciated.. thanks
You simply need and extra event subscription to Button.Click event
private void Form1_Load(object sender, EventArgs e)
{
p = new PrintClass();
button1.Click += cls.printEventHandler;
}
To handle all the buttons on the form you can write a simple snippet like
public Form1()
{
InitializeComponent();
foreach (Button btn in Controls.OfType<Button>())
{
btn.Click += cls.printEventHandler;
}
}
To know which button was clicked you can write PrintClass as
class PrintClass
{
public void printEventHandler(object sender, EventArgs e)
{
Button btn = (Button) sender;
//btn.Name <-- Control name;
//btn.Text<-- Control Text;
}
}
One thing that I am not understanding is, why do you need a extra class if you need to output the result on the same form.
My suggest would be, not to create an extra class just for handling all the Button.Click event
This can work the way you want : I am removing the need for extra class
public Form1()
{
InitializeComponent();
foreach (Button btn in Controls.OfType<Button>())
{
btn.Click += HandleAllButtonClicks;
}
}
private void HandleAllButtonClicks(object sender, EventArgs e)
{
Button btn = (Button) sender;
TboxPrint.AppendText(String.Format("Button Clicked : Name = {0}, Text = {1}", btn.Name, btn.Text));
}

How do you associate click events of buttons created in code in C# with methods?

I'm building a Windows Phone app and I can't make a dynamically created Button associate with its event handler.
The code I'm using is:
public partial class MainPage : PhoneApplicationPage
{
Button AddButton
public MainPage()
{
CreateInterestEntry();
}
private void CreateInterestEntry()
{
EntrySegment = getEntrySegment();
ContentPanel.Children.Add(EntrySegment);
}
private void AddButton_Click(Object sender, RoutedEventArgs e)
{
//Stuff to do when button is clicked
}
private Grid getEntrySegment()
{
Grid EntrySegment = new Grid();
//Creating the grid goes here
AddButton = new Button();
AddButton.Content = "Add";
AddButton.Click += new EventHandler(AddButton_Click);
return EntrySegment;
}
}
}
With this code it complains that no overload for AddButton_Click matches delegate "System.EventHandler".
It's virtually identical to the code under Examples here at msdn, with the exception I've changed the argument type in AddButton_Click from EventArgs to RoutedEventArgs as otherwise Visual Studio tells me that it cannot implicitly convert from System.EventHandler to System.RoutedEventHandler.
Thanks in advance
Try this:
AddButton.Click += new RoutedEventHandler(AddButton_Click);
And the Click Event Handler:
void AddButton_Click(object sender, RoutedEventArgs e)
{
}

How to check from which button I called form in C#?

I have "formA" and 2 buttons on it (button1 and button2). What I want to do is:
When I click on button1 to call "formB" display text written in label1.
When I click button2 to call the same form ("formB") hide label1 and display label2.
The problem is that I don't know how to check what button is clicked on "formA".
Edit: Thanks very much folks for the quick answer. Problem is solved!
This is where events come in handy:
public class FormA
{
private void button1_Click(object sender, EventArgs e)
{
formB.Button1WasClicked();
}
private void button2_Click(object sender, EventArgs e)
{
formB.Button2WasClicked();
}
}
public class FormB
{
public void Button1WasClicked()
{
label2.Visible = false;
label1.Visible = true;
label1.Text = "Button 1 was clicked!";
}
public void Button2WasClicked()
{
label1.Visible = false;
label2.Visible = true;
label2.Text = "Button 2 was clicked!";
}
}
button1 and button2 have their own separate Click event handlers. This way we can differentiate the two when they are clicked.
If you have the same event handler for both buttons (as mentioned in one of the comments), you can identify them with the sender parameter using:
Object.ReferenceEquals(sender, button1);
or
Object.ReferenceEquals(sender, button2);
Then your code would look like this:
private void button_Click(object sender, EventArgs e)
{
if (Object.ReferenceEquals(sender, button1))
{
formB.Button1WasClicked();
}
else
{
formB.Button2WasClicked();
}
}
FormB can't find out, the buttons are a private implementation details of FormA. They might not even be a button, surely you are going to add a menu or a toolbar to FormA some day.
The workaround becomes much simpler if you stop thinking of "calling a form". You never call a form, you create an instance of it. And then you make it visible by calling its Show() method. Lots of things you can do in between those two steps.
Add a public method to FormB. For lack of a better name:
public void MakeLabel2Visible() {
this.label1.Visible = false;
this.label2.Visible = true;
}
Now it becomes simple. Implement button2's Click event handler like this:
private void button2_Click(object sender, EventArgs e) {
var frm = new FormB();
frm.MakeLabel2Visible();
frm.Show();
}
Adding another constructor to a form that lets you initialize it differently is another very common approach. These are just classes, standard programming techniques are appropriate.
Because you are using winforms you can do all this very easily due to the fact that you have a stateful environment.
Assuming a very basic set up with:
event handlers in the code behind of form a
a reference to an instance of form b in form a (or the button click creating such an instance)
a method to use in form b to pass it data
Your code will be something like this:
public partial class FormA : Form
{
private FormB formB;
public FormA()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (formB == null || formB.IsDisposed)
{
formB = new FormB();
}
formB.UpdateLabel("Button A");
formB.Show();
}
private void button2_Click(object sender, EventArgs e)
{
if (formB == null || formB.IsDisposed)
{
formB = new FormB();
}
formB.UpdateLabel("Button B");
formB.Show();
}
}
public partial class FormB : Form
{
public FormB()
{
InitializeComponent();
}
public void UpdateLabel(string message)
{
label1.Text = message;
}
}
Of course, there are lots of improvements to this - using events and alerts more intelligently and refactoring to remove duplication, but this is a basic example of the sort of things you can do.

Categories

Resources