'I want to automatically press a button on the form as soon as it is opened

In the program, I have an alert that appears to the user when the first time he opens the program, if it has expired products, an alert message appears like this enter image description here

If the user presses yes, the screen will open with the products that have expired during the week This screen opens

enter image description here

Here are his options 3 options that he sees the end of the day or to end during the current month. Automatic, so I want the first thing to press Yes, the exception to the offer opens on the button (this week) that displays the current week The code I used

 if (tbl001.Rows.Count >= 1)
        {
            if (XtraMessageBox.Show("لديك منتجات ستنتهى مدة صلاحيتها خلال هذا الإسبوع هل تريد الإطلاع عليها", "تاكيد", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                Frm_ProductsExpiration frm = new Frm_ProductsExpiration();
                frm.ShowDialog();
                frm.simpleButton1.PerformClick();
            }
        }

But unfortunately it didn't work for me. I want as soon as the screen is opened, the button I want is automatically pressed



Solution 1:[1]

The call to ShowDialog prevents the following line, frm.simpleButton1.PerformClick(), from executing until after frm is closed.

You could just add a handler to the Shown event on Frm_ProductsExpiration and call simpleButton1.PerformClick() there.

For example, in your existing code simply remove the call to frm.simpleButton1.PerformClick().

if (tbl001.Rows.Count >= 1)
{
    if (XtraMessageBox.Show("???? ?????? ?????? ??? ???????? ???? ??? ??????? ?? ???? ??????? ?????", "?????", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
    {
        Frm_ProductsExpiration frm = new Frm_ProductsExpiration();
        frm.ShowDialog();
        // Note that we've removed the call to frm.simpleButton1.PerformClick()
    }
}

Then, you use the designer to add a handler to the Shown event on Frm_ProductsExpiration, and call simpleButton1.PerformClick() there.

private void Frm_ProductsExpiration_Shown(object sender, EventArgs e)
{
    simpleButton1.PerformClick();
}

If you can't use the designer for some reason, you could just manually add the handler in the constructor of Frm_ProductsExpiration.

public Frm_ProductsExpiration()
{
    InitializeComponent();
    Shown += Frm_ProductsExpiration_Shown;
}

private void Frm_ProductsExpiration_Shown(object sender, EventArgs e)
{
    simpleButton1.PerformClick();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1