How can I programmatically manipulate Anchor styles

Platform: WinForms| Category: Controls

You can do this using the bitwise operators &, | and ^ ( And, Or and Xor (or &, Or, ^) in VB.Net). Here is code that will toggle label1 being anchored on the left.

[C#]
	private void button1_Click(object sender, System.EventArgs e)
	{
		if ((label1.Anchor & AnchorStyles.Left) == 0)
		{	//add it
			label1.Anchor = label1.Anchor | AnchorStyles.Left;
		}
		else if ((label1.Anchor & AnchorStyles.Left) != 0)
		{	//remove
        			label1.Anchor = label1.Anchor ^ AnchorStyles.Left;
		}
	}

[VB.NET]


	Private Sub button1_Click(sender As Object, e As System.EventArgs)
		If(label1.Anchor And AnchorStyles.Left) = 0 Then
			’add it
			label1.Anchor = label1.Anchor Or AnchorStyles.Left
		ElseIf(label1.Anchor And AnchorStyles.Left) <> 0 Then
			’remove
			label1.Anchor = label1.Anchor Xor AnchorStyles.Left
		End If
	End Sub ’button1_Click

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.