Stop Triggering Event on Page Load - c#

I have a CheckBox with IsChecked="true" property and Checked event:
<CheckBox Checked="myChBox_Checked" IsChecked="True" />
I don't want to trigger the Checked event on page load. Because I use other Controls in the method and I get NullReferenceException:
private void myChBox_Checked(object sender, RoutedEventArgs e) {
myComboBox ... // NullReferenceException
}
What am I supposed to do to stop the triggering from startup?

You can for example:
subscribe in Page.Loaded event:
this.Loaded += (sender, e) => myChBox.Checked += myChBox_Checked;
or maybe better just check in your event for null:
private void myChBox_Checked(object sender, RoutedEventArgs e)
{
if (something == null) return;
myComboBox ... // NullReferenceException
}

You can just check for null reference in the event handler, or assign it in the page Loaded event handler:
public partial class MyPage : Page
{
public MyPage()
{
InitializeComponent();
this.Loaded += page_Loaded;
}
private void page_Loaded(object sender, RoutedEventArgs e)
{
myChBox.Checked += myChBox_Checked;
}
private void myChBox_Checked(object sender, RoutedEventArgs e)
{
if (myComboBox != null)
{
myComboBox ... // Should not be null, but check anyway
}
}
}

Related

Winui3 OnClosin in the single page

My app has multiple pages.
When I press the Close key in the toolbar, how can I detect the OnClosing event in the single page to avoid closing the app instead of going back to the MainWindow with "this.Frame.GoBack();" ?
I can only catch OnClosing on MainWindow
You could store a reference to the window in a property or field in your App.xaml.cs class as suggested here and then handle the Closing event of the window in the Page class something like this:
public sealed partial class MainPage : Page
{
private Window _parentWindow;
public MainPage()
{
this.InitializeComponent();
this.Loaded += OnLoaded;
this.Unloaded += OnUnloaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
_parentWindow = (Application.Current as App)?.m_window;
if (_parentWindow != null)
_parentWindow.Closed += OnWindowClosed;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
if (_parentWindow != null)
_parentWindow.Closed -= OnWindowClosed;
}
private void OnWindowClosed(object sender, WindowEventArgs args)
{
// Prevent the window from being closed based on some logic of yours...
args.Handled = true;
}
}
You can use the Unloaded event on Pages.
*.xaml
<local:TestPage Unloaded="TestPage_Unloaded" />
*.xaml.cs
private void TestPage_Unloaded(object sender, RoutedEventArgs e)
{
// Do your page closing work here...
}

Create an ButtonClick Event in UserControl in C#

I create the ButtonClick event in the UserControl below and want to handle it in a Form, but I get an error that says 'The name UserControl1.ButtonClick' does not exist in the current context.
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
public event EventHandler ButtonClick;
private void btnUpdate_Click(object sender, EventArgs e)
{
if (this.ButtonClick != null)
this.ButtonClick(this, e);
}
Form:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick);
protected void UserControl_ButtonClick(object sender, EventArgs e)
{
//handle the event
}
Form:
public PatientNumber()
{
InitializeComponent();
userControl11.updateButton.Click += button_Click;
}
protected void button_Click(object sender, EventArgs e)
{
    //handle the event
}
UserControl:
public Button btnUpdatee
{
get
{
return btnUpdate;
}
set
{
btnUpdate = value;
}
}
This code worked.
Thank you

Creating custom event for hiding a control not working

Here is my code in my userControl
public partial class UserControlHomeScreen : UserControl
{
public event EventHandler SomethingHappened;
public void DoSomething()
{
EventHandler handler = SomethingHappened;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
public void HandleEvent(object sender, EventArgs args)
{
MessageBox.Show("Wafak.");
}
public UserControlHomeScreen()
{
InitializeComponent();
}
private void btnAverageDailyBal_Click(object sender, EventArgs e)
{
this.Tag = 0;
this.Hide();
}
private void btnComputeTransferPricing_Click(object sender, EventArgs e)
{
this.Tag = 1;
this.Hide();
}
}
And here is my code in my main form
private void HomeScreen()
{
uHomeScreen = new UserControlHomeScreen();
uHomeScreen.Dock = DockStyle.Fill;
//uHomeScreen.Disposed += new EventHandler(uHomeScreen_Disposed);
uHomeScreen.SomethingHappened += new EventHandler(uHomeScreen_SomethingHappened);
panelMain.Controls.Add(uHomeScreen);
}
void uHomeScreen_SomethingHappened(object sender, EventArgs e)
{
MessageBox.Show("throw new NotImplementedException();");
}
What i want to happen is that when the usercontrol is hidden i want to fire an event in my main form but does not work, what am i missing? please help. thanks!
Your naming convention for event raiser (DoSomething) is confusing, your code doesn't call DoSomething (or raise the event SomethingHappened), so how could it fire for you? Add the following code in your user control class:
//override the OnVisibleChanged
protected override void OnVisibleChanged(EventArgs e){
if(!Visible) DoSomething();
}

How to work with delegates and event handler for user control

I have created a user control that contains a button.
I am using this control on my winform which will be loaded at run time after fetching data from database.
Now I need to remove a row from a datatable on the Click event of that button.
The problem is that how do I capture that event in my form. Currently it goes in that user control's btn click event defination.
You can create your own delegate event by doing the following within your user control:
public event UserControlClickHandler InnerButtonClick;
public delegate void UserControlClickHandler (object sender, EventArgs e);
You call the event from your handler using the following:
protected void YourButton_Click(object sender, EventArgs e)
{
if (this.InnerButtonClick != null)
{
this.InnerButtonClick(sender, e);
}
}
Then you can hook into the event using
UserControl.InnerButtonClick+= // Etc.
It's not necessary to declare a new delegate. In your user control:
public class MyControl : UserControl
{
public event EventHandler InnerButtonClick;
public MyControl()
{
InitializeComponent();
innerButton.Click += new EventHandler(innerButton_Click);
}
private void innerButton_Click(object sender, EventArgs e)
{
if (InnerButtonClick != null)
{
InnerButtonClick(this, e); // or possibly InnerButtonClick(innerButton, e); depending on what you want the sender to be
}
}
}
Just modernizing ChéDon's answer, here is how you can do it in 2018:
public class MyControl : UserControl
{
public event EventHandler InnerButtonClick;
public MyControl()
{
InitializeComponent();
innerButton.Click += innerButton_Click;
}
private void innerButton_Click(object sender, EventArgs e)
{
InnerButtonClick?.Invoke(this, e);
//or
InnerButtonClick?.Invoke(innerButton, e);
//depending on what you want the sender to be
}
}

C# .net framework2.0 how to dynamically assign methods to an event

VS2008, C#, .NET FRAMEWORK2.0
I want this: click button1, webbrowser1._DocumentCompleted() event revokes doA(); click button2, it revokes doB(); click button3, it revokes doC().
I know how to do it using JAVA and I guess C# has this mechanism too. Could anyone give me some idea or better, show me some example?
myButton.Click += myButton_Click;
protected void myButton_Click(object sender, EventArgs e) {}
To Add a handler
button.Click += buttonClickEventHandler;
To remove a handler
button.Click -= buttonClickEventHandler;
To add to these answers, you can also add an anonymous method to an event:
myButton.Click += (object sender, EventArgs e) => {
MessageBox.Show("MASSIVE ERROR!");
};
What this means is that you can effectively call a method even if it does not match the appropriate event handler signature:
myButton.Click += (object sender, EventArgs e) => {
DoA();
};
Or (without using a lamba expression):
myButton.Click += delegate(object sender, EventArgs e) {
DoA();
};
If you want to add event handlers to a control, which is what I think you are describing, you can easily do this. One common approach is to assign control event handlers in the code behind during page load:
protected void Page_Load(object sender, EventArgs e)
{
//add the event handler for the click event. You could provide other
//logic to determine dynamically if the handler should be added, etc.
btnButton1.Click += new EventHandler(btnButton1_Click);
btnButton2.Click += new EventHandler(btnButton2_Click);
btnButton3.Click += new EventHandler(btnButton3_Click);
}
protected void btnButton1_Click(object sender, EventArgs e)
{
//get the button, if you need to...
Button btnButton1 = (Button)sender;
//do some stuff...
DoA();
}
protected void btnButton2_Click(object sender, EventArgs e)
{
//do some stuff...
DoB();
}
protected void btnButton3_Click(object sender, EventArgs e)
{
//do some stuff...
DoC();
}
private void DoA() {}
private void DoB() {}
private void DoC() {}
Declaring an event
public class MyClass1
{
...
public event EventHandler<EventArgs> NotifyValidate;
protected void RaiseNotifyValidate(EventArgs e)
{
if (NotifyValidate != null)
{
NotifyValidate(this, e);
}
}
...
}
Firing that event in your code
...
RaiseNotifyValidate(new EventArgs()); //EventArgs could be more sophisticated, containing data etc..
Registering for that event in your code:
...
MyClass aObj = new MyClass();
aObj.NotifyValidate += new EventHandler(onNotifyValidate);
...
private void onNotifyValidate(object sender, EventArgs e)
{
//do what you need to
}
As Dan pointed out, with Lambda expressions you can define events like
aObj.NotifyValidate += (s,ev) =>
{
//handle your event
};

Categories

Resources