ernest
ernest

Reputation: 1724

Is there a quick way of adding an event to many controls at once in WPF?

I have 400+ textboxes on a page. The page is meant to be an exact replica of a paper form. The user is going to edit all of the fields and then save the data to the DB. The data is being pulled down into a DataTable from a SQL DB.

I'm planning on saving the data via the same DataTable or just via a bulk update. Not 100% on that. But, I need to get access to that data. And maybe I'm not doing this next best part the best and if I'm not, I'd appreciate it if I was informed of a better way.

When the DataTable gets the data, I assign each field into the appropriate control. Below is an example of how the data is being added.

foreach (DataRow CDR in ClaimDataTable.Rows){
    if (CDR["BoxNumber"].ToString() == "1.1")
        this.Box1_1.Text = CDR["DataValue"].ToString();
    if (CDR["BoxNumber"].ToString() == "1.2")
        this.Box1_2.Text = CDR["DataValue"].ToString();
    if (CDR["BoxNumber"].ToString() == "1.3")
        this.Box1_3.Text = CDR["DataValue"].ToString();

I wrote some code to automatically create that code. So I didn't manually write all 400+ lines.

What I was thinking, was that I could add a LostFocus event to each TextBox. Then when the control loses focus, I would create a class with a box name and the box value. Add that to a list and when they're ready to save, just loop through the list and do the bulk update with the BoxNumber and the box data.

Would that be feasible? Or is there a better method?

Thanks!

Upvotes: 0

Views: 133

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31721

When the DataTable gets the data, I assign each field into the appropriate control.

WPF is data binding and one does not generally load controls as you mentioned. Why is the code not binding to each control to a property which adheres to INotifyPropertyChanged?

  1. Have the page's DataContext (DC) point to an instantiated class which adheres to InotifyPropertyChanged interface. The setting of the DC in that fashion will allow all controls on the page to use its datacontext by default.
  2. In the class to be instantiated for the DC create a member property which calls PropertyChanged when the value is set using the INotifyPropertyChanged system.
  3. Bind each TextBox Text property to that property on the class.

Then each control which needs that value will display it automatically after it has been set such as in this example.

<TextBlock Name="tbHeader"
           Text="{Binding CDRData}" />

Then one only has to write the value to the property named CDRData once and all textboxes bound get the value.

Upvotes: 2

brunnerh
brunnerh

Reputation: 185553

  1. Look into event routing.
  2. You should not create and access individual text-boxes but let the framework create them via datatemplating a collection, your above code is ze horror.

Upvotes: 3

Related Questions