Right-aligned labels in WinForms

后端 未结 9 1498
甜味超标
甜味超标 2021-01-07 15:59

The most obvious way to right-align a Label in WinForms doesn\'t work: setting anchor to Top/Bottom Right and TextAlign to TopRight. If the text changes the lab

9条回答
  •  独厮守ぢ
    2021-01-07 16:46

    • dynamically created label's default autosize is false.
    • if label's autosize is false. it contains extra empty space.
    • that tricks you to think its doesnt right align properly. to diagnose it, set the label's backColour to lightgreen

     int rowIndex=1;
    
     var lbx = new Label();
     lbx.AutoSize = true;          // default is false.
     lbx.BackColor = Color.Green;  // to see if it's aligning or not
     lbx.Text = "Iam  Autosize=true";
     lbx.Anchor = AnchorStyles.Right;
     tlPanel.Controls.Add(lbx, 0, rowIndex);
    
     var dtp = new DateTimePicker();
     dtp.Anchor = AnchorStyles.Left;
     tlPanel.Controls.Add(dtp, 1, rowIndex);
    
    
      //--- row 2  autosize false
     rowIndex=2;
      var lbx2 = new Label();
     lbx2.AutoSize = false;          // default is false.
     lbx2.BackColor = Color.Green;  // to see if it's aligning or not
     lbx2.Text = "AutoSz=false";
     lbx2.Anchor = AnchorStyles.Right;
     tlPanel.Controls.Add(lbx2, 0, rowIndex);
    
     var dtp = new DateTimePicker();
     dtp.Anchor = AnchorStyles.Left;
     tlPanel.Controls.Add(dtp, 1, rowIndex);
    

提交回复
热议问题