Mama, you sound tired! (How could that be, with a two-year-old? :^D)
You have a whole lot to teach your daughter, so when this sort of thing happens, you can be flexible and change to a different lesson. It will still be a good lesson.
When someone wants to give your daughter a treat, with your permission (!), teach her first of all to say, "Thank you." The rest of the lesson is, "Wasn't he a kind man? Sometimes people we don't even know do kind things, and it's right to thank them. This won't happen every day - not by a long shot - so let's be grateful when it happens. Now let's go home. You can play with your trinket there." Will your daughter listen to you? Yes.
At the park, it was good that you recognized that the boy was being very gracious. "Gracious" is a good word for your girl to learn. I think I would have answered the mom when she said not to worry about the sand castle, "Thanks, but we need to go now." I would thank the boy as well, and have my daughter thank him, too. Then I would take us home - or to another part of the park. I would say, "Wasn't that a nice boy? He was very gracious to let you hit his castle that he was working so hard on building. When you're his age I hope you will know how to be that gracious to children." It could be that the boy's mama had been trying to teach him to let others join in his games, so you could have been helping her.
Sometimes you have to be flexible and adjust your lessons to the situation. Happily, in neither case was your teaching being thwarted or undermined deliberately. You are still teaching your daughter, because it was *your* decision to let her have or do what she did; they offered and you decided.