title: C# windows form repaint button with old text
body: <p>I have been searching all morning for a solution to this and still can't figure it out, so this is going to seem like a duplicate question but it's not.</p>
  
  <p>I am programming a windows form application in Visual Studio Pro 2015 and it has about 40 buttons with flat styling. The button forecolor is supposed to be white but most of them are disabled when the form opens so they show black text. After researching some this morning I found out that I needed to repaint the buttons to get the text color right...which works well when you change it for every single button individually. Here is the code that I'm using for that:</p>
  
  <pre><code>    private void someButton_Paint(object sender, PaintEventArgs e)
      {
          Button btn = (Button)sender;
          // make sure Text is not also written on button
          btn.Text = string.Empty;
          // set flags to center text on button
          TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;   // center the text
          // render the text onto the button
          TextRenderer.DrawText(e.Graphics, "SomeButtonText", btn.Font, e.ClipRectangle, System.Drawing.Color.White, flags);
      }
  </code></pre>
  
  <p>I don't want to have to do that for every single button. Its messy and it seems like I should be able to write a generalized version of this, set all the button's paint event to a single method, and have it be the painter for all of them. That mostly works also, but there's one little hitch: I want to set each button's text to the same as it was before the paint but no matter what I've tried I can't seem to get this to work. The text just gets set to an empty string. Here is the code I'm using for this:</p>
  
  <pre><code>    private void allButtons_Paint(object sender, PaintEventArgs e)
      {
          Button btn = (Button)sender;
  
          string str = btn.Text; // This is the simplest way I've tried to get the button text
  
          // make sure Text is not also written on button
          btn.Text = string.Empty;
          // set flags to center text on button
          TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;   // center the text
          // render the text onto the button
          TextRenderer.DrawText(e.Graphics, str, btn.Font, e.ClipRectangle, System.Drawing.Color.White, flags);
      }
  </code></pre>
  
  <p>Does anybody know a way to make this work? I know I probably could have just implemented that method for every button by this point but I really want this other way to work because it bugs me that something so seemingly simple is giving me this much trouble.</p>