I have a label that I want to right align to be able to place aligned to a text box.
The Designer in Visual Studio 2010 Express have generated this code for me
this.lblAddData.AutoSize = true;
this.lblAddData.Location = new System.Drawing.Point(167, 452);
this.lblAddData.Name = "lblAddData";
this.lblAddData.Size = new System.Drawing.Size(25, 14);
this.lblAddData.TabIndex = 5;
this.lblAddData.Text = "text";
this.lblAddData.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
[text][textbox]
In the code I change the text programmaticly
lblAddData.Text = "a very long text";
but the text is hiding behind the texbox that I have placed next to the label on the
right side.
[a ver][textbox]
Have someone experienced the same problem before?
I know it is missing information so ask me if you need more info.
Best Regards
Görgen
Well, I spotted the error myself; AutoSize was set to true, that is default behavour
this.lblAddData.AutoSize = true;
When I changed this to false it worked as I assumed it should.
The TextAlign property controls how the text is aligned within the label:
Gets or sets the alignment of text in the label.
If you change the length of the text you need recalculate the Location of the label which is always top left.
I've found this Code Project article which, while probably over the top for what you want, states:
Moreover, if you are going to change the label text (e.g., when localizing the application) or text alignment, you'll have to resize/reposition controls. Therefore, I have created this simple label that takes care of such details.
(my bold)
So you could use the same algorithm to reposition your label.
Related
As can be seen in the image above, I have four labels that are on top of some PictureBoxes. Note that I added the blue text and arrow in the image in Paint; they are not elements of the form.
By default, these labels have their Visible parameters set to False and their Text parameters are set to being empty. At specific points in the program, one of the labels is selected to both have Visible set to True and to have a 3-digit-or-less number alongside a percent sign(in the format ### % in which # is a digit) in black size 12.75 Microsoft Sans Serif font.
However, only the top label(the one being pointed at by the blue arrow) actually becomes visible and displays its text when its parameters are changed in this way. The top image below shows what the top label looks like when this happens, while the bottom image below shows what the other three labels look like when the same process is applied to any of them.
Ignoring the difference in aspect ratio between the two images, the only important difference between the two is that in the first one, the label is visible and is displaying "75 %", while in the second one, the label is not visible so there is no number or percent sign.
I know for a fact that in the second instance the label's Visible property is set to True and its text is set to "75 %" through debugging, but none of this shows up when the form is running. Another thing that I have determined through debugging is that this issue is either caused by or at least apparent in the function below, since this function is the only code block that:
a) is used in every instance in which the labels are set to having Visible be True and their text being set to that "### %" format, and also
b) distinguishes between the different labels.
private void UpdateHpText(PictureBox HPBox) //the function in question
{
//this conditional tree takes "HPBox," one of the Pictureboxes that the labels overlap(the green bars), and uses it to decide which label needs to be altered
if(HPBox == side2HPbox1)
{
//Side2HPText1 is the top label, Side2HPText2 is the next from the top label, and etc.
Side2HPText1.Visible = HPBox.Visible; //I know from debugging that HpBox.Visible should be set to True in the instance I am having trouble with
side2HPbox1DisplayNum = (BasicProcess.side2[0].HP.value * 100) / (BasicProcess.side2[0].HP.max); //calculates the number displayed in the Label's text
Side2HPText1.Text = side2HPbox1DisplayNum + " %"; //sets the label's text
//in the above instance, the label should have Visible set to True, and its Text should be assigned to a string. However, I'm not having issues with this block.
}
//so tell me, is there ANY difference between the above block and the below block other than:(see differences in documentation of each line)
else if (HPBox == side2HPbox2)
{
Side2HPText2.Visible = HPBox.Visible; //a different label is targeted here
side2HPbox2DisplayNum = (BasicProcess.side2[1].HP.value * 100) / (BasicProcess.side2[1].HP.max); //BasicProcess.side2[1] is being used instead here because it targets the object that is assigned to the label in this block, and side2HPBoxDisplayNum is just used in the final line of this block for the displayed string
Side2HPText2.Text = side2HPbox2DisplayNum + " %";
//from what I see, both blocks are functionally the same, and I also know that to be the case from debugging, but when the form runs, I get a completely different result for each block.
}
else if (HPBox == side2HPbox3)
{
Side2HPText3.Visible = HPBox.Visible;
side2HPbox3DisplayNum = (BasicProcess.side2[2].HP.value * 100) / BasicProcess.side2[2].HP.max;
Side2HPText3.Text = side2HPbox3DisplayNum + " %";
}
else
{
Side2HPText4.Visible = HPBox.Visible;
side2HPbox4DisplayNum = (BasicProcess.side2[3].HP.value * 100) / BasicProcess.side2[3].HP.max;
Side2HPText4.Text = side2HPbox4DisplayNum + " %";
}
}
As you can read in the code above, there shouldn't be any difference between what the top label looks like when its block runs and what the second label looks like when its block runs, but there is. This makes me think that I might be having a GUI error that I'm not noticing in my code. One thing I've learned about GUI in Winforms is that that threading can have an impact on how the GUI updates itself. For that reason, I will post the relevant code in my program below that uses Async and Await, which might have an impact on threading.
Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Visible = true; //sets one of the green bar PictureBox's Visible parameter to True
await Task.Delay(500); //waits half a second
targetList[0] = char1ChosenSkill.effect(targetList[0]); //this can be ignored since it does not effect the PictureBox or Label
Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Image = UpdateHpBar(targetList[0], BasicProcess.side2); //runs UpdateHPBar
UpdateHpText(Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])]);
await Task.Delay(1500); //waits 1.5 seconds
Side2HPBoxList[BasicProcess.side2.IndexOf(targetList[0])].Visible = false; //sets one of the green bar PictureBox's Visible back to false
Menu2Background.Visible = (char2 != null); //this can be ignored since it does not effect the PictureBox or Label
However, I don't think that Task.Delay could genuinely scuff up the GUI that much, especially considering that it runs for each and every label the same way.
Another potential reason for my program not running correctly is the properties of the labels. For that reason, I will post them below. Please don't forget that even though the Text and Visible elements are set to being empty and False respectively here, they should be set to containing a string and being True at the point in the program that I am having trouble with.
//
// Side2HPText1
//
this.Side2HPText1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Side2HPText1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(2)))), ((int)(((byte)(218)))), ((int)(((byte)(55)))));
this.Side2HPText1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Side2HPText1.Location = new System.Drawing.Point(1109, 127);
this.Side2HPText1.Name = "Side2HPText1";
this.Side2HPText1.Size = new System.Drawing.Size(58, 26);
this.Side2HPText1.TabIndex = 66;
this.Side2HPText1.Visible = false;
//
// Side2HPText2
//
this.Side2HPText2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Side2HPText2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(2)))), ((int)(((byte)(218)))), ((int)(((byte)(55)))));
this.Side2HPText2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Side2HPText2.Location = new System.Drawing.Point(1109, 279);
this.Side2HPText2.Name = "Side2HPText2";
this.Side2HPText2.Size = new System.Drawing.Size(58, 26);
this.Side2HPText2.TabIndex = 70;
this.Side2HPText2.Visible = false;
I haven't noticed any differences here that could be relevant to my issue, but maybe someone will.
Anyhow, if I haven't provided enough relevant information here, feel free to ask me to provide more.
EDIT:
I'm not entirely sure how to provide a reproducible example without sharing absolutely all of my code. I will start documenting a big chunk of it and tack it to the bottom of this post by the end of today, but it will take time. Hopefully doing that will help
EDIT 2:
Actually, I can provide some more info before I do that. Firstly, when I said that I determined that the Visible parameter was set to True and the Text was set to a string by debugging, I meant that I set up a breakpoint and looked in the Autos field in Debug mode to determine that this was the case.
I also have brought the Labels to the front several times now(thinking that maybe I did it wrong before or something), so I am confident that they are brought to the front. I also put a line of code in UpdateHPText saying:
Side2HPText2.Parent = Side2HPText2.Parent;
so I could see that value in the Autos field. It turns out that this value was set to the form it's on(BattleTemplate4), so I think that that is fine.
EDIT 3:
Here's a pastebin link to the InitializeComponent function since it won't fit the character limit: https://pastebin.com/WRRJ5n4d (a commenter asked for it)
EDIT 4:
Okay, I think I've determined that it's a painting issue. I'm going to switch over to having the text either drawn on since I don't think it's worth the trouble to resolve an issue that can be mollified by trying something else that's equally functional.
EDIT 5:
NEVERMIND! I didn't expand to the two comments that weren't visible, and used the .BringToFront() function on the text in UpdateHPText, and it worked. Thanks #Idle_Mind for resolving my issue.
I also have brought the Labels to the front several times now(thinking
that maybe I did it wrong before or something), so I am confident that
they are brought to the front.
But have you tried doing that in the CODE itself after setting the .Text property?
...
Side2HPText2.Text = side2HPbox2DisplayNum + " %";
Side2HPText2.BringToFront();
#Idle_Mind that worked, thank you.
WinForms controls cannot overlap. There is a special-case for "transparent" control backgrounds, but that's just an trick (a "transparent" background control requests its parent form repaint its background first, then the control paints itself).
This is because WinForms controls are their own hWnd surfaces, and WinForms does not support transparent control backgrounds or alpha-blending.
It was pretty tough to think a title for this question so I'll try to make a better job explaining myself here.
I needed to create a dynamic Windows Form so that when checkbox gets checked/unchecked, few input fields appear/disappear. As far as I know FlowLayoutPanel seemed to be the best tool to achieve this. So I created a Custom User Control that included a Label and a Textbox. I designed this new Control in VS2013 desginer view:
Since the text on the label can vary in length it is important that textbox begins only when label has already ended. However the result I get at the moment looks like this:
The label should read out "ConnField" instead of "ConnFie". I tried adding these items in FlowLayoutPanel but that resulted in label and textbox not lining up correctly. Are there any attributes/properties that should be set in order to get the expected result? Should I use a container that does it all for me?
On a side note, if there are any other methods to dynamically show/hide elements in the fashion I described above I'd be very happy to use those instead.
For perfect fits you can script the TextChanged event(s) to make sure the TextBox always sits in place and keeps a nice size as well..
I have placed a Label and a TextBox into a Panel for testing. You will probaly not need or want the textBox1_TextChanged event but it was nice for testing..:
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.Text = textBox1.Text; // this is for testing
}
private void label1_TextChanged(object sender, EventArgs e)
{
textBox1.Left = label1.Right + 6; // <= this is what you need
textBox1.Width = panel2.Width - label1.Width - 8; // <= this is nice to have
}
Of course your offsets may vary..and obviously the Label has AutoSize = true
Edit
Since you commented on the problem of getting the TextBoxes aligned with each other across rows here are a few thoughts about this problem. As Hans noted, you can't have it all:
Complete freedom for the Labels' content
Perfect fits
And aligned Textboxes
The three goals conflict. So you need to make compromises:
If you can restrict the content to a fixed maximum, the result will look best
Sometimes it helps to have a collegue or even a user look at the content to find a shorter way to express the meaning
Ellipsis or abbreviations may help. I both cases you should set a ToolTip to show the full content
Another option is to switch to a narrower Font for some Labels
Instead of one fixed Label size maybe 2 or 3 will help: The look will be a bit jagged but will look a lot better than with completely free sizes.
There is a similar question like mine here in Stackoverflow but it only explains how to change it in XAML. I want to know how can I change it in code.
Here is a image that shows how I do it in XAML using Blend:
Link for full size: https://snag.gy/4Skk4.jpg
Basically I want to change the background of a button's pressed state in C# but I can't seem to find any examples on the Internet. It must be in code because sometimes the image of the button will change therefore the button's pressed image must change as well.
The following code is just to change the image of the button and it's just the start.
image.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(#"images/Button-warning-icon.png", UriKind.Relative));
image.Stretch = Stretch.Uniform;
buttonWarnings.Background = image;
If I understand you correctly, you are trying to change the appearance of the Button control in a "pressed" visual state.
I'm not near my dev computer to try it out, but to "unblock you" I'll give a direction.
First, as you noticed in your Blend screenshot, each visual state is represented with a Storyboard, which defines how various properties change. In your case, you're looking to change Background property.
The VisualStateGroups and their states are defined by the control. You can override them when you re-template the control. So, retemplate the button control using Blend with "Edit Template"->"Edit Copy".
Then, in code, you should be able to do the following:
1) Get visual states (this would not work unless you re-template the control, AFAIK)
var visualStateGroups = VisualStateManager.GetVisualStateGroups(buttonWarnings);
2) Get the VisualStateGroup of "CommonStates" from the visualStateGroups
collection
var commonStatesGroup = visualStateGroups.Find((g) => ((VisualStateGroup)g).Name == "CommonStates") as VisualStateGroup;
3) Get the "Pressed" VisualState:
var pressedVisualState = commonStatesGroup.Find((vs) => ((VisualState)vs).Name == "Pressed") as VisualState;
4) Change the storyboard of that state
pressedVisualState.Storyboard = newStoryboardWithCustomImageBackgroundProperty;
(Disclaimer: I'm not near in a computer to try it now - it's all in theory)
There are many examples to be found on the internet!
Take a look at some:
http://mobile.dzone.com/articles/windows-phone-buttonimage
http://loekvandenouweland.com/index.php/2011/01/windows-phone-image-button/
Actually its quite simple,
While in button pressed state....see part 3 in the image you uploaded above.
Above all the colors there is a row containing 5 icons.
Click on 4th icon.
it will show you option to choose image as background.
I have a multiline TextBox called Console. While running, this textbox is being filled up with some communications data. I use
TextBox.AppendText("txt\r\n");
to add a line to it and that allows me to have it autoscroll down. My problem is I want to be able to not have it autoscroll down. So I thought I would try
TextBox.Text += "text";
But that scrolls you to the beginning of the box. My latest attempt was to use TextBox.SelectionStart to save the position before I wrote and restore it back to that after, but that didn't seem to make a difference and still brings me back to the beginning of the text.
int txtPosition = Console.SelectionStart;
Console.Text += "TextToAdd";
Console.SelectionStart = txtPosition;
Ideally I want to just be able to have the box stay where ever it happens to be and not scroll to the beginning or end of the text.
I think you need to you a richtextbox instead of a generic textbox and this will provide you with the functionality you desire.
Enjoy!
For a WinForms textbox, you may should able to do this:
textBox.SelectionStart = 0;
textBox.ScrollToCaret(); // force current position back to top
What I am trying to achieve is a form that has a button on it that causes the Form to 'drop-down' and become larger, displaying more information. My current attempt is this:
private void btnExpand_Click(object sender, EventArgs e)
{
if (btnExpand.Text == ">")
{
btnExpand.Text = "<";
_expanded = true;
this.MinimumSize = new Size(1, 300);
this.MaximumSize = new Size(int.MaxValue, 300);
}
else
{
btnExpand.Text = ">";
_expanded = false;
this.MinimumSize = new Size(1, 104);
this.MaximumSize = new Size(int.MaxValue, 104);
}
}
Which works great! Except for one small detail... Note that the width values are supposed to be able to go from 1 to int.MaxValue? Well, in practice, they go from this.Width to int.MaxValue, ie. you can make the form larger, but never smaller again. I'm at a loss for why this would occur. Anyone have any ideas?
For the record: I've also tried a Form.Resize handler that set the Height of the form to the same value depending on whatever the boolean _expanded was set to, but I ended up with the same side effect.
PS: I'm using .NET 3.5 in Visual Studio 2008. Other solutions are welcome, but this was my thoughts on how it "should" be done and how I attempted to do it.
Edit: Seems the code works, as per the accepted answers response. If anyone else has troubles with this particular problem, check the AutoSize property of your form, it should be FALSE, not TRUE. (This is the default, but I'd switched it on as I was using the form and a label with autosize also on for displaying debugging info earlier)
As per the docs, use 0 to denote no maximum or minimum size. Tho, I just tried it and it didn't like 0 at all. So I used int.MaxValue like you did and it worked. What version of the the framework you using?
Actually, having a look at the MinimumSize and MaximumSize (.NET 3.5) in reflector its pretty clear that the designed behaviour is not quite the same as the docs suggest. There is some minimum width constraints determined from a helper class and 0 has no special meaning (i.e. no limit.
Another note, I see in your code above that you are Expanding or Contracting based upon the text value of your Button, this is a bad idea, if someone comes along later and changes the text in the designer to say, "Expand" instead of < without looking at your code it will then have an unexpected side effect, presumably you have some code somewhere that changes the button text, it would be better to have a state variable somewhere and switch on that.