Is it possible to change the function of a button when I click on another button?

487 views Asked by At

Let's say I have an add and edit button. both of these buttons bring up the same form and have the same save button inside the form. when I click on save after clicking the add button it inserts into the database and when I click on the save button after clicking the edit button it updates the records. would this be possible or do I have to create a new similar form for this?

1

There are 1 answers

0
ingham On

You should have a class defining your form, with a set of fields and a Save button.

The save button on your form does not insert the data directly but instead, it calls an event with the data user typed.

Then your application creates an instance of this form, register an event handler et does what it wants (insert or update for instance)

A very quick example (pseudo-code):

class FormData {
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

class Form {
    public Form(FormData data) {
        //...

        field1.Text = data.Field1;
        field2.Text = data.Field2;
    }

    TextField field1;
    TextField field2;
    //...

    public event EventHandler<FormData> Saved;

    void OnButtonClicked() {
        var data = new FormData();
        data.Field1 = field1.Text;
        data.Field2 = field2.Text;
        
        if (Saved != null)
            Saved.Invoke(this, data);
    }
}

class Application {
    void Add() {

        //An empty data, since you are creating a new one
        var data = new FormData();

        //Show your form
        var form = new Form(data);
        form.Saved += OnAddData;
        form.Show();
    }
    void OnAddData(object sender, FormData data) {
        //INSERT into database    
    }

    void Edit() {

        //A data pre-filled with the fields of your row
        var data = new FormData();
        data.Field1 = yourDataFromYourRow1;
        data.Field2 = yourDataFromYourRow2;

        //Show your form
        var form = new Form(data);
        form.Saved += OnEditData;
        form.Show();
    }
    void OnEditData(object sender, FormData data) {
        //UPDATE into database    
    }
}