How to Delete a user control through key down event - c#

I have a User control which is a label along with a text box. this control will created dynamically in a form. i want to delete this control using delete key press.the Click event is used to focus on the control and keypress method used to trigger the keydown event. Here is my code
private void usereditFieldControl_Click(object sender, EventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
editFieldControl.KeyDown += new KeyEventHandler(Key_pressed);
}
private void Key_pressed(object sender, KeyEventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
if (e.KeyCode == Keys.Delete)
{
editFieldControl.Dispose();
}
}

You can use the following code. "sender" can be cast to the more generic "Control" class:
private void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Delete) {
Control ctl = (Control)sender;
ctl.Dispose();
this.Controls.Remove(ctl);
}
}
If your control is created dinamically at runtime, do not forget to add a handler to KeyDown event, with something like this:
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

private void usereditFieldControl_Click(object sender, EventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
editFieldControl.KeyDown += new KeyEventHandler(Key_pressed);
}
private void Key_pressed(object sender, KeyEventArgs e)
{
EditFieldControl editFieldControl = (EditFieldControl)sender;
if (e.KeyCode == Keys.Delete)
{
//Find control
for (int i = 0; i < editFieldControl.Parent.Controls.Count(); i++) {
if (editFieldControl.Parent.Controls[i].Name == editFieldControl.Name) {
//Unhook events to prevent memory leaks
editFieldControl.KeyDown -= new KeyEventHandler(Key_pressed);
//Remove control from collection
editFieldControl.Parent.Controls.RemoveAt[i];
break;
}
}
//repaint
this.Invalidate();
}
}
Untested, written on iPhone

Related

Is there a way to handle all the number buttons in one keyboard event instead of doing for each buttons in a calculator?

Instead of copying and pasting for each number is there a method that could reference to all buttons?
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D5)
{
Five.PerformClick();
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D5)
{
Five.PerformClick();
}
}
Firstly, the enum values Keys.D0 to Keys.D9 have sequential integer values. You can abuse this knowledge to turn the KeyCode directly into an array index.
var buttons = new Button[] {Zero, One, ... etc ...};
if(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9){
var index = (int)e.KeyCode - (int)Keys.D0;
var button = buttons[index];
button.PerformClick();
}
if(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9){
// similar to the above
}
Or you could rearrange your code. Create a separate method for doing the work of "user entered a digit". Then call that method from both the button click event and form key event.
private void HandleDigit(int value){
// todo
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9){
var value = (int)e.KeyCode - (int)Keys.D0;
HandleDigit(value);
}
}
Maybe this can give you an idea -- instead of the code you show something like
Button.PerformClick('5');
would do what you want. Or even
Button.PerformNumberClick(5);
and if + is preseed
Button.PerformOperatorClick('+');
You can create and event for the first button and then tie all the calculator buttons to that event, inside the event you know what key (number) is pressed.
Here is a code that could be useful, i only added two buttons to test it and notice when i live the form im releasing handles unsubscribing the events:
using System;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CmdButton1.KeyDown += CmdButtonKeyDown;
CmdButton2.KeyDown += CmdButtonKeyDown;
}
private void CmdButtonKeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.NumPad1 || e.KeyCode == Keys.NumPad2 )
MessageBox.Show("KeyPressed is " + e.KeyCode.ToString());
}
private void Form1_Leave(object sender, EventArgs e)
{
CmdButton1.KeyDown -= CmdButtonKeyDown;
CmdButton2.KeyDown -= CmdButtonKeyDown;
}
}
}

C# trigger event for datagridview cell text changed [duplicate]

i am making a windows form application in which i used a datagridview.
i want that when i write something in textbox in datagridview,than a messagebox appears containing the string i wrote..
ican't get my text in textchanged event..
all thing must be fired in textchanged event..
here is my code:-
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
TextBox tb = (TextBox)e.Control;
tb.TextChanged += new EventHandler(tb_TextChanged);
}
}
void tb_TextChanged(object sender, EventArgs e)
{
//listBox1.Visible = true;
//string firstChar = "";
//this.listBox1.Items.Clear();
//if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
string str = dataGridView1.CurrentRow.Cells["Column2"].Value.ToString();
if (str != "")
{
MessageBox.Show(str);
}
}
void tb_TextChanged(object sender, EventArgs e)
{
var enteredText = (sender as TextBox).Text
...
}
Showing MessageBox in TextChanged will be very annoying.
Instead you could try it in DataGridView.CellValidated event which is fired after validation of the cell is completed.
Sample code:
dataGridView1.CellValidated += new DataGridViewCellEventHandler(dataGridView1_CellValidated);
void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}

keydown event is not working on editable texbox on grid in c# windows application

I want to add a new row in the grid when i press a enter key in a texbox in the gridview
private void dgReceipt_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dgReceipt.CurrentCell.ColumnIndex == 5)
{
DataGridViewTextBoxEditingControl txtcontrol = e.Control as DataGridViewTextBoxEditingControl;
if (txtcontrol != null)
{
txtcontrol.KeyPress += new KeyPressEventHandler(txtcontrol_KeyPress);
}
}
}
private void txtcontrol_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
dgReceipt.Rows.Add(1);
}
}

Making a panel draggable

I am creating a "cropping tool", and i need to make a panel that contains 2 buttons draggable.
Until now i've tried something like this, but the change location event happens only when i click the right button of the mouse...
this.MouseDown += new MouseEventHandler(onRightClickMouse);
private void onRightClickMouse(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Point localMouseClickPoint = new Point(e.X, e.Y);
panel1.Location = localMouseClickPoint;
}
}
My question: How can i make that panel draggable in my form?(I mean click on the panel then drag it to a location).
Try something like this:
delegate void updatePanelCallback();
panel1.MouseDown += new MouseEventHandler(onMouseDown);
panel1.MouseUp += new MouseEventHandler(onMouseUp);
System.Timers.Timer runTimer = new System.Timers.Timer(100);
runTimer.Elapsed += new ElapsedEventHandler(onTimerElapsed);
private void onMouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
{
return;
}
runTimer.Enabled = false;
}
private void onMouseUp(object sender, MouseEventArgs e)
{
runTimer.Enabled = false;
}
public void updatePanelLocation()
{
if (this.InvokeRequired)
{
this.Invoke(new updatePanelCallback(updatePanelLocation), new object[] {});
}
else
{
Cursor curs = new Cursor(Cursor.Current.Handle);
panel1.Location = curs.Position;
}
}
private void onTimerElapsed(object source, ElapsedEventArgs e)
{
updatePanelLocation();
}
You could try something in two steps, preparing the action on MouseDown event and finishing it on MouseUp.

how to reset the focus to last entered textbox in windows application

I have two TextBoxes and a button control in the form. When the button is clicked the name of the last entered TextBox should be displayed in a MessageBox. At the same time I need to reset the focus to last entered TextBox.
string str=string.Empty;
bool foc;
In button click I wrote the following code
if (MessageBox.Show("You want to reset or continue", "control",
MessageBoxButtons.OKCancel) == DialogResult.Cancel)
{
if (foc== true)
{
textBox1.Focus();
}
else
{
textBox2.Focus();
}
}
When I clicks on cancel button the focus should be into textbox which is entered at last
private void textBox1_Enter(object sender, EventArgs e)
{
str = textBox1.Name;
foc= textBox1.Focus();
}
private void textBox2_Enter(object sender, EventArgs e)
{
str= textBox2.Name;
foc= false;
}
Other than the above lines of code is there any other possibility to focus into the textbox, but when number of textboxes increases how i need to write the conditions.
If I am having textbox,combobox,listbox,checkbox or any other controls in the form then how to find in which control the user enterd at last and set focus to that control by using any function instead of writing in every control Enter event
You can handle Leave event of the TextBoxes to store the Last TextBox Control.
Try this:
this.btnSubmit.Click += new System.EventHandler(this.Submit_Click);
this.btnCancel.Click += new System.EventHandler(this.Cancel_Click);
this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
this.textBox2.Leave += new System.EventHandler(this.textBox2_Leave);
TextBox txtLast = new TextBox();
private void textBox1_Leave(object sender, EventArgs e)
{
txtLast = (TextBox)sender;
}
private void textBox2_Leave(object sender, EventArgs e)
{
txtLast = (TextBox)sender;
}
private void Submit_Click(object sender, EventArgs e)
{
MessageBox.Show(txtLast.Text);
}
private void Cancel_Click(object sender, EventArgs e)
{
txtLast.Focus();
}
public bool textBox1WasLastFocused = false, textBox2WasLastFocused = false; // Global Declaration
void textBox2_GotFocus(object sender, EventArgs e)
{
textBox2WasLastFocused = true;
textBox1WasLastFocused = false;
}
void textBox1_GotFocus(object sender, EventArgs e)
{
textBox1WasLastFocused = true;
textBox2WasLastFocused = false;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1WasLastFocused)
MessageBox.Show("textbox1 was ladst focused !");
else if(textBox2WasLastFocused)
MessageBox.Show("textbox2 was ladst focused !");
}

Categories