event handler not working with dynamically generated xaml button - c#

private void createCarers()
{
foreach (Carer c in CarerManager.Carers.Values)
{
Button x = new Button
{
Content = c.name,
MinHeight = 50,
Tag = c,
Margin = new Thickness(0, 0, 0, 10)
};
x.Click += new RoutedEventHandler(carerClick);
carersPanel.Children.Add(x);
}
}
private void carerClick(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.Shutdown();
}
Ok so createCarers is called when the window is initialised.
Why does this not work? The shutdown thing is just a test but it does not work.

Related

How do I find button that enabled timer

I was wondering if it was possible to find which button enabled a timer in C#. Here's my code:
private void button1_MouseEnter(object sender, EventArgs e) {
fadeIn_Timer.Start();
}
int a;
private void fadeIn_Timer_Tick(object sender, EventArgs e) {
var btn = (Button)sender;
a += 30;
if (a >= 255) {a = 255; }
btn.BackColor = Color.FromArgb(a, 255, 255, 255); // would change back color of button1
btn.Refresh();
if (a == 255) { a = 0; fadeIn_Timer.Stop(); }
}
I already tried var btn = (Button)sender;, but I don't seem to have any luck. If anyone can help me out that would be great!
I suggest you save the Button in the MouseEnter event handler, then you have it for later. Something like this:
private void button1_MouseEnter(object sender, EventArgs e) {
fadeIn_Timer.Start();
timerButton = (Button)sender;
}
int a;
Button timerButton;
private void fadeIn_Timer_Tick(object sender, EventArgs e) {
a += 30;
if (a >= 255) {a = 255; }
timerButton.BackColor = Color.FromArgb(a, 255, 255, 255); // would change back color of button1
timerButton.Refresh();
if (a == 255) { a = 0; fadeIn_Timer.Stop(); }
}
That should get you started.
Here's an example for how you could implement this. The confusion is that Timer is a WinForms control but you need the System.Threading.Timer class for this to work.
So create a WinForms solution. Add a Form with a button (button1 in my case) and add the code below in the code behind of the form. When you click the button it should alternate it's background between black and white.
public partial class Form1 : Form
{
System.Threading.Timer Timer { get; set; }
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Timer = new System.Threading.Timer(button =>
{
Button myButton = (Button)button;
if (myButton.BackColor == Color.Black)
myButton.BackColor = Color.White;
else
myButton.BackColor = Color.Black;
}, button1, 1000, 1000);
}
}
You can pass the button object when you initiate the Timer like so:
Timer = new Timer(someObjectThatWasPassed =>
{
// Code here can access 'someObjectThatWasPassed'
}, someObjectToPass, 1000, 1000);
Make sure that 'Timer' is a field in your class i.e.:
public class SomeClass
{
Timer Timer { get; set; }

Reflection added Delegate not firing

This is the code.
For example purposes, NewButton will have the name "Add", the SubMenuButtonNamesList is a list of strings containing the names of the buttons that I will be creating, afterwards I wanted to add the handler to these buttons based on the methods found in the mainwindow, matched by their names.
I think I did it properly since the button does have this handler added, but when I click the button nothing happens, it should show me a messagebox saying "yes".
public void Add_Method(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Yes");
}
public MainWindow()
{
InitializeComponent();
//Create all sub-menu buttons
foreach (var element in SubMenuButtonNamesList)
{
Button NewButton = new Button()
{
Background = new SolidColorBrush(new Color { A = 100, R = 231, G = 233, B = 245 }),
FontFamily = new FontFamily("Century Gothic"),
Content = element,
FontSize = 14,
Height = 30,
Width = Double.NaN,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center
};
NewButton.Name = element.Trim();
try
{
MethodInfo method = typeof(MainWindow).GetMethod(NewButton.Name + "_Method");
Delegate myDelegate = Delegate.CreateDelegate(typeof(MouseButtonEventHandler), this, method);
NewButton.MouseLeftButtonDown += (MouseButtonEventHandler)myDelegate;
}
catch (Exception e)
{
}
SubMenuButtonsList.Add(NewButton);
}
}
It appears the MouseLeftButtonDown event for Button (didn't check for anything else), if added this way will not fire, however if you do it for the Click event, it will fire properly, see below snippet of the modifications:
MethodInfo method = typeof(MainWindow).GetMethod(NewButton.Name + "_Method");
Delegate myDelegate = Delegate.CreateDelegate(typeof(RoutedEventHandler), this, method);
NewButton.Click += (RoutedEventHandler)myDelegate;
And the method:
public void Add_Method(object sender, RoutedEventArgs e)
{
MessageBox.Show("Yes");
}

Call object after created by action in C# Winform

I have an action for my button in c# Winform like this:
private void btnAction_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(508, 12 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel2.Controls.Add(tbxdg);
cx++;
}
Now I want to get text from the textbox that i've created by clicking my button. I've tried call the textbox by the name that i given to it in the button click action but it's not working.
u can try this:
var textBoxText = panel2.Controls.Find("name of textbox", false).First().Text;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int cx = 0;
private void button1_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(0, 0 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel1.Controls.Add(tbxdg);
cx++;
}
private void button2_Click(object sender, EventArgs e)
{
label1.Text = string.Empty;
foreach (TextBox tb in panel1.Controls)
{
label1.Text += $"{tb.Name} - {tb.Text}\n";
}
}
}
Demo
Instead of searching the control name in the panel, another approach is to add all the dynamic text boxes to global List<TextBox>
Please read comments inside the example:
private int cx;
private List<TextBox> DynamicTextBoxesList = new List<TextBox>();
private void btnAction_Click(object sender, EventArgs e)
{
TextBox tbxdg = new TextBox();
tbxdg.Name = "tbx_DG" + cx.ToString();
tbxdg.Location = new Point(508, 12 + (40 * cx));
tbxdg.Size = new Size(200, 24);
tbxdg.Font = new Font("Tahoma", 10);
panel2.Controls.Add(tbxdg);
// add to list
DynamicTextBoxesList.Add(tbxdg);
cx++;
}
// button event for example how to use DynamicTextBoxesList
private void btnExampleFoaccesingTextBoxes_Click(object sender, EventArgs e)
{
if (DynamicTextBoxesList.Count > 0)
{
foreach (TextBox t in DynamicTextBoxesList)
{
MessageBox.Show(t.Text);
}
// or you can find by name for example you need cx=1:
var txtbox = DynamicTextBoxesList.Where(x => x.Name == "tbx_DG1").FirstOrDefault();
if (txtbox != null)
{
MessageBox.Show(txtbox.Text);
}
}
}

set backcolor to disabled button windows forms

I have a button in my windows forms which I need to enable/disable. When disabled I need to change its backcolor and retain the forecolor to show that it is disabled.
Following is what I tried. this retains the forecolor(white here), but does not change the backcolor
private void button1_EnabledChanged(object sender, System.EventArgs e)
{
buttonScan.ForeColor = Color.White;
buttonScan.BackColor = Color.Aqua;
}
private void button1_Paint(object sender, PaintEventArgs e)
{
var btn = (Button)sender;
var drawBrush = new SolidBrush(btn.ForeColor);
var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
e.Graphics.DrawString(btn.Text, btn.Font, drawBrush, e.ClipRectangle, sf);
drawBrush.Dispose();
sf.Dispose();
}
I need to change the backcolor when the button is disabled
f you want to use your custom color, you need to set UseVisualStyleBackColor to false or the color will only be applied to the button upon mouse over.
a simple test uploaded to GitHub
public partial class mainForm : Form
{
Random randonGen = new Random();
public mainForm()
{
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e)
{
populate();
}
private void populate()
{
Control[] buttonsLeft = createButtons().ToArray();
Control[] buttonsRight = createButtons().ToArray();
pRight.Controls.AddRange(buttonsRight);
pLeft.Controls.AddRange(buttonsLeft);
}
private List<Button> createButtons()
{
List<Button> buttons = new List<Button>();
for (int i = 1; i <= 5; i++)
{
buttons.Add(
new Button()
{
Size = new Size(200, 35),
Enabled = true,
BackColor = GetColor(),
ForeColor = GetColor(),
UseVisualStyleBackColor = false,
Left = 20,
Top = (i * 40),
Text = String.Concat("Button ", i)
});
}
return buttons;
}
private Color GetColor()
{
return Color.FromArgb(randonGen.Next(255), randonGen.Next(255), randonGen.Next(255));
}
}

WPF: how to call method by setting tag of a dynamically created buttons

3 problems in my WPF(window phone) simple project. I have spent lot of time by solving it but no specific result found..
In my cs file I have Created bunch of dynamic buttons...I crated with for loop and set tags for each dynamic button.
My cs File code is here.
private void Grid_View_Btn_1_Click(object sender, System.Windows.RoutedEventArgs e)
{
//Grid ButtonsAddition
Dispatcher.BeginInvoke(() =>
{
string[] Trade = new string[] { "Portfolio Display", "Trade Idea Entry", "Trade Idea Monitor", "Historical Performance", "Intraday Performance", "Stock Performance" };
StackPanel panel = new StackPanel();
panel.Orientation = System.Windows.Controls.Orientation.Vertical;
//panel.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
//panel.VerticalAlignment = System.Windows.VerticalAlignment.Top;
int i;
for (i = 0; i < Trade.Length; i++)
{
Button btn = new Button() { Content = Trade[i] };
btn.Margin = new Thickness(0, -10, 0, -10);
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("C:/Users/HafizArslan/Documents/Visual Studio 2012/Projects/AimPass/AimPass/Images/tabbar_btn_blue.png", UriKind.Relative));
btn.Background = brush;
btn.Width = 190;
btn.Height = 75;
btn.FontSize = 14;
btn.FontWeight = light;
btn.FontStretch = Fill;
btn.HorizontalAlignment = HorizontalAlignment.Center;
btn.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
// btn.CornerRadius = new CornerRadius(15);
btn.BorderThickness = new Thickness(1, 1, 1, 1);
btn.Tag = i.ToString();
btn.Click += new RoutedEventHandler(abc_click);
panel.Children.Add(btn);
}
grid.Children.Add(panel);
});
}
private void abc_click(object sender, EventArgs e)
{
}
There are 6 buttons creted.
the problem is I want to perform different actions with button...I have set Tags but I dont know how can I access an actions with buttons Tag..?
I mean I want something like this...!!
private void abc_click(object sender, EventArgs e)
{
// If(btn.Tag==1)
{
//Some Code Here
}
else
if(btn.Tag==2) {
//Perform other Function
}
} Etc.....?
and other problem is I have made a image brush..Assign exact path of image...for every created button background....But Image is not attached...
Kindly tell me about these 2 problems...
You have sender in handler, you can type cast sender to button and access Tag property from it:
private void abc_click(object sender, EventArgs e)
{
Button button = (Button)sender;
if(Convert.ToInt32(button.Tag) == 1)
{
.....
}
}
In your for loop, you can associate handler to the button.
Such as:
Button btn = new Button() { Content = Trade[i] };
btn.Margin = new Thickness(0, -10, 0, -10);
if(<something>)
btn.Click += YourEventHandler1;
if(<something2>)
btn.Click += YourEventHandler2;
If you want to access tag property, you need to cast the sender to Button, as so:
private void abc_click(object sender, EventArgs e)
{
var btn = (Button)sender;
}
you should go with this
var tag=((sender as Button).Tag).ToString();
////now use a switch
Switch(tag)
{
case "1":
//Action
break;
case "2":
//Acrion
break;
//more cases
}
hope this helps.
if for all created buttons the event is same then One approach could be to get the tag in the event like this
int tag=Convert.ToInt32((sender as Button).Tag);
now use a switch
switch(tag)
{
case 1:
//Action
break;
case 2:
//Acrion
break;
//more cases
}
hope this helps.

Categories

Resources