How to keep button enabled after closing the form - button

I'm trying to make a system and I'm having trouble with buttons being disabled.
I have a function that makes the button on a another form enable the button on the main form but whenever I get back to the main form the button becomes disabled again.
How do I keep this permanent even after closing the program? Can I save it in a database to keep its function enabled even if its default is disabled?
Here's the picture of what it looks like:
Thanks for the help.

Take two buttons - "button1" and "button2" on "MainForm" Form.
Set property Enabled=false for "button1"
MainForm.cs
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 oFrm2 = new Form2();
oFrm2.evtFrm += new ShowFrm(oFrm2_evtFrm);
oFrm2.Show();
}
void oFrm2_evtFrm()
{
button1.Enabled = true;
}
}
Take one button - "button1" on "Form2" Form.
Form2.cs
public delegate void ShowFrm();
public partial class Form2 : Form
{
public event ShowFrm evtFrm;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (evtFrm != null)
{
evtFrm();
}
}
}
MainForm will display first.
Click on "button2" to display "Form2".
On "Form2", click on "button1" to make enable "button1" of "MainForm"
If you want to make "button1" enable permanent, you have to store value - "button1" is enable or disable.

Related

C#, Xamarin Forms: No Custom TextChangedEvent Raised on initialization

I'm creating an Xamarin.Forms MVVM App (only using Android) which needs certain buttons to be outlined red, whenever their text property holds a specific value. (Purpose: alert the user to press the button and select a value, which will change the Button Text Property and therefore remove the red outline)
To achieve this I've create the following documents:
A custom button CButton that extents the default Button:
public class CButton : Button
{
// this Hides the Default .Text-Property
public string Text
{
get => base.Text;
set
{
base.Text = value;
TextChangedEvent(this, new EventArgs());
}
}
// The Raised Event
protected virtual void TextChangedEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> handler = TextChanged;
handler(sender, e);
}
public event EventHandler<EventArgs> TextChanged;
}
A custom behavior makes use of the raised TextChangedEvent
public class ButtonValBehavior : Behavior<CButton>
{
protected override void OnAttachedTo(CButton bindable)
{
bindable.TextChanged += HandleTextChanged;
base.OnAttachedTo(bindable);
}
void HandleTextChanged(object sender, EventArgs e)
{
string forbidden = "hh:mm|dd.mm.yyyy";
if (forbidden.Contains((sender as CButton).Text.ToLower()))
{
//Do when Button Text = "hh:mm" || "dd.mm.yyyy"
(sender as CButton).BorderColor = Color.Gray;
}
else
{
//Do whenever Button.Text is any other value
(sender as CButton).BorderColor = Color.FromHex("#d10f32");
}
}
protected override void OnDetachingFrom(CButton bindable)
{
bindable.TextChanged -= HandleTextChanged;
base.OnDetachingFrom(bindable);
}
}
The relevant parts of the ViewModel look the following:
public class VM_DIVI : VM_Base
{
public VM_DIVI(O_BasisProtokoll base)
{
Base = base;
}
private O_BasisProtokoll _base = null;
public O_BasisProtokoll Base
{
get => _base;
set
{
_base = value;
OnPropertyChanged();
}
}
Command _datePopCommand;
public Command DatePopCommand
{
get
{
return _datePopCommand ?? (_datePopCommand = new Command(param => ExecuteDatePopCommand(param)));
}
}
void ExecuteDatePopCommand(object param)
{
//launch popup
var p = new PP_DatePicker(param);
PopupNavigation.Instance.PushAsync(p);
}
}
The .xmal looks the following (b is the xmlns of the Namespace):
<b:CButton x:Name="BTN_ED_Datum"
Text="{Binding Base.ED_datum, Mode=TwoWay}"
Grid.Column="1"
Command="{Binding DatePopCommand}"
CommandParameter="{x:Reference BTN_ED_Datum}">
<b:CButton.Behaviors>
<b:ButtonValBehavior/>
</b:CButton.Behaviors>
</b:CButton>
This solution works fine whenever the input is caused by user interaction. However, when a Value is assigned during the initialization of the Page no red outline is created, in fact the TextChangedEvent isn't raised. By using breakpoints I noticed that during initialization the Text Property of CButton is never set, eventhough it actually will be in the view.
Despite fiddling around with my solution I cannot make this work on initialization. I tried to work around this issue by outlining every button by default in their constructor, however this will outline every button red, even when their text value doesn't require them to be.
How can I achieve my initial goal?
Many thanks in advance!
It's been a while but if I recall correctly what I ended up doing was:
Changing the new Text-Property of my custom Button to CText and
Making sure that I have Mode=TwoWay activated for any Element, that doesn't have it enabled by default. (Look up Binding modes on msdn for more)
making CText a bindable property of CButton
My custom button now looks the following:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace EORG_Anton.Model
{
public class CButton : Button
{
public static readonly BindableProperty CTextProperty =
BindableProperty.Create(nameof(CText),
typeof(string),
typeof(CButton),
default(string),
BindingMode.TwoWay,
propertyChanged: OnTextChanged);
private static void OnTextChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (CButton)bindable;
var value = (string)newValue;
control.CText = value;
}
public string CText
{
get => base.Text;
set
{
base.Text = value;
TextChangedEvent(this, new EventArgs());
}
}
protected virtual void TextChangedEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> handler = TextChanged;
handler(sender, e);
}
public event EventHandler<EventArgs> TextChanged;
}
}

How to use PKPaymentButton in Xamarin.Forms

I have a page in Xamarin.Forms in which I have to show PKPaymentButton by using the same PKPaymentButton class which is a child of UIButton in PassKit.
I have written a custom ButtonRenderer and trying to convert the button into PKPayment button.
I got so far that in custom renderer we can change the appearance of a button but can we use something like creating a new button instance in my case PKPaymentButton and replace it with Button.
UPDATE-
I have achieved this by-
public class ApplePayButtonRenderer : Xamarin.Forms.Platform.iOS.ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var button = new PKPaymentButton(PKPaymentButtonType.Buy, PKPaymentButtonStyle.Black);
SetNativeControl(button);
}
}
}
Now I am trying to get its click into Xamarin.Forms
You could use Messaging Center to send message when you click the payment Button.
in Custom Renderer
var button = new PKPaymentButton(PKPaymentButtonType.Buy, PKPaymentButtonStyle.Black);
button.TouchUpInside += Button_TouchUpInside;
SetNativeControl(button);
private void Button_TouchUpInside(object sender, EventArgs e)
{
MessagingCenter.Send<Object>(this,"PayButtonClick");
}
in Forms
Add the following code to the constructor of the ContentPage which contains the Payment Button
public xxxPage()
{
InitializeComponent();
MessagingCenter.Subscribe<Object>(this, "PayButtonClick",(args)=> {
//do some thing you want
});
}

Get e parameter from a button that hasn't been clicked

Is there a way that I could access the e event arguments for a button that has not been clicked?
I need to delete multiple entries in a gridview by clicking a button and having it simulate clicking the delete button for each selected entry, but I can't use performClick, so I'm trying to call the actual method that deletes each one. However, that method requires an "e As System.Web.UI.WebControls.GridViewCommandEventArgs" parameter and I can't figure out how to get that.
You won't be able to access the EventArgs parameter.
I'd suggest you design your code like this:
public class MyClass
{
private ListView listView;
protected void OnClick(EventArgs e)
{
performAction();
}
private void performAction()
{
listView.deleteSelectedItems();
}
}
Don't implement functionality you are going to need somewhere else in delegates. Instead call this functionality inside the delegates' body. This way you can reuse performAction() somewhere else ..
Your problem calling delete button can be resolved if you add one check box in each row of datagrid and on click of button Delete you can perform delete operation for the checked rows in following manner
Protected void btnDelete_Click(object sender, EventArgs e)
{
for(int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if(chkDelete != null)
{
if(chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
ids.Add(strID); //ids can colletion of any type
}
}
}
}
Now send ids to any function to perform delete.

Change label during button execution

I have a "Connect" button which calls internal logic for network connection
I have this button which starts network connection.
Button connectButton = new Button("Connect");
connectButton.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
actiontarget.setText("Successful Connection Test!");
}
});
How I can change the button label during the action execution with label "Cancel"?
And also how I can cancel the action when the button label is "Cancel"? Maybe I need to call specific action when the button label is different?
You could extend your code snippet with the logic below. Haven't tried it but I think it should work, even I would suggest using Injection.
private final String CONNECT = "connect";
private final String DISCONNECT = "disconnect";
Button connectButton = new Button(CONNECT);
connectButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e)
{
if (connectButton.getText().equals(CONNECT)) {
do_something();
actiontarget.setText(DISCONNECT);
} else {
do_something_else();
actiontarget.setText(CONNECT);
}
}
});
Another Idea would be to use a ToggleButton:
In your FXML:
<ToggleButton fx:id="btnConnect" alignment="CENTER" maxHeight="1" maxWidth="1" onAction="#actionClickedConnectBtn" text="connect"/>
In your Code:
#FXML
public void actionClickedConnectBtn(ActionEvent event) {
if (btnConnectGpsd.isSelected()) {
do_something();
} else {
do_something_else();
}
}
You can use a Boolean flag to indicate which action to execute when the button is clicked; if the flag is true, then execute your cancel action and set the flag to false, setting your button's text to "Connect". If the flag is instead false, execute your connection action and set the flag to true, setting your button's text to "Cancel".

Setting parent page controls visibility from Child user control page

I have a parent page Page1 which has button1. Page1 has a usercontrol uc1. uc1 has an update panel inside which a grid grid1 is present. I am trying to set Page1.button1's visibility to false, depending on the row command event(there are some if conditions in the row command event) of uc1.grid1. I am setting Page1.button1's visibility in the following way:
Create a IsButton1Visible property in uc1. Set the property in UC1.Grid1.RowCommand to false, on page1 PreRender event, access IsButton1Visible and set Page1.button1 visibility.
Even though in quick watch Page1.button1 visibility is set to false at the line of assignment, when I see the UI, it is still visible. I don't know what I am doing wrong. Or the way that I am getting hold of button1 and its visibility is not correct.
In general can we set a Parent page's control's property from a user control during the user control event?
If you use the event-driven model approach
Delegate/EventArgs code:
public class ButtonVisiblityEventArgs : EventArgs
{
public ButtonVisiblityEventArgs(bool visible)
{
this.Visiblity = visible;
}
public bool Visiblity { get; private set; }
}
public delegate void UpdateParentButtonVisibilityEventHandler(object sender, ButtonVisiblityEventArgs args);
User control code:
public event UpdateParentButtonVisibilityEventHandler RaiseUpdateParentButtonVisibilityEvent;
private void RequestParentButtonVisibilityChange(bool setVisible)
{
if (RaiseUpdateParentButtonVisibilityEvent != null)
{
RaiseUpdateParentButtonVisibilityEvent(this, new ButtonVisiblityEventArgs(setVisible));
}
}
And in your command handler, just call:
RequestParentButtonVisibilityChange(false);
whenever you want to hide the button. On your page:
protected void Page_Load(object sender, EventArgs e)
{
this.RaiseUpdateParentButtonVisibilityEvent += new UpdateParentButtonVisibilityEventHandler(uc_RaiseUpdatecurrentDisplayPanelRequestEvent);
}
private void uc_RaiseUpdatecurrentDisplayPanelRequestEvent(object sender, ButtonVisiblityEventArgs args)
{
button1.Visible = args.Visiblity;
}
If the problem you are having is that your button lives outside of the update panel, you can do the following. Page codebhind:
protected void Page_Load(object sender, EventArgs e)
{
string hideScript = string.Format("function updateButtonVisibility( visibility ) {{ var button = $('#{0}'); if (visibility) {{ button.show(); }} else {{ button.hide(); }} }}", this.button1.ClientID);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "updateButtonVisibility", hideScript, true);
}
And in your user control command handler:
bool shouldButtonBeVisible = false; //update this appropriately in your logic
ScriptManager.RegisterStartupScript(this, this.GetType(), "upUpdateButtonVisibility", "updateButtonVisibility(" + shouldButtonBeVisible ? "true" : "false" + ");", true);
Please note that this creates a TIGHT dependency between your UC and the page. It requires that any page that consumes this control has registered this script. There are ways to get around this (such as setting a function script callback to call, detecting if that javascript function exists, etc), but this should at least get you moving.
If there is something specific on the page after your update panel finishes that you could key off, it might be better to register an end request handler
$(function() { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(updatePanelEndRequestHandler); } );
function updatePanelEndRequestHandler() {
var shouldBeVisible = $('.MyClassThatSaysIShouldntAllowMoreButtons').length > 0; //do some checking on the grid
updateButtonVisibility(shouldBeVisible);
}
you can put your user controls inside panels on your parent pages and change the visibility.
e.g.
<asp:Panel runat="server" ID="pnlQuote">
...
</asp:Panel>
<asp:Panel runat="server" ID="pnlContact">
<uc1:ContactForm runat="server" ID="ContactForm " />
</asp:Panel>
From the child control you can make a button click event which does something like this
protected void btnBackToQuote_Click(object sender, EventArgs e)
{
Panel pnlQuote = this.Parent.FindControl("pnlQuote") as Panel;
Panel pnlContact = this.Parent.FindControl("pnlContact") as Panel;
pnlQuote .Visible = true;
pnlContact.Visible = false;
}

Resources