简体   繁体   中英

Different AcceptButton for different Panels on Form

I have a form with a Search button & Submit button, they are sitting on different panels but in the same form. I want to use the AcceptButton property of the Form with both buttons based on criteria.

The user will search for a ticket using the box on the right panel, which will populate the datagridview below. The user will then select a row, which I have bound to the text boxes on the left panel. The New Asset textbox is blank, so the user will have to populate that before hitting submit.

Is there anyway to bind the AcceptButton Property to the search textbox (right panel) if the new asset number textbox is null and then bind the property to the submit button (left panel) after the user populates the text box.

Sorry if this is hard to understand. I am still learning c# and all of the things I can do with it.

剪掉它的应用程序,这样你就可以得到一个更好的主意

Note: While I also believe the UI design in the question case can be improved, but in general having multiple default button for different parts of a page can be considered as a normal requirement, like html form elements which are supposed to run their submit button code if you press enter on any form element, while you can have multiple form on a single page.

What you need to do is overriding ProcessDialogKey and check if the first panel contains focus then perform click of the first button and if the second panel contains focus then perform click of the second button:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.Enter)
    {
        if (panel1.ContainsFocus)
        {
            button1.PerformClick();
            return true;
        }
        if (panel2.ContainsFocus)
        {
            button2.PerformClick();
            return true;
        }
    }
    return base.ProcessDialogKey(keyData);
}

You also have the option of handling Enter event of controls and assign AcceptButton of the form based on the focused control. But above/below solutions are more general with less code.

Note - Creating a Panel class having AcceptButton property

Apart from above solution, as a more reusable solution for those who wants to handle such cases by less code, you can use such panel class having AcceptButton property:

using System.Windows.Forms;
public class MyPanel : Panel
{
    public Button AcceptButton { get; set; }
    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            AcceptButton?.PerformClick();
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM