phpnet
phpnet

Reputation: 923

How to set a button to a max left in panel c#

I have a button already in panel which is not visible until scrolled(as the view size of panel is smaller than x-cordinate of buttonA) . I want to place a button beyond buttonA . How to do it ? I am using this but it only puts the button to the left of view of control not to the internal max width.

I want it to be generic if any button get beyond the max internal width the next button should go even left to that button . Cant use dock as i want the same function for top placing also .

"New edit to question "

The buttons are generated after every click and they have random width . The button can be deleted but the new button should be added to the max width occupied so far , if recent button is deleted the next button should take place after the second most left button

button1.Left = buttonA.Parent.Size.Width+button1.Width;

enter image description here

Upvotes: 4

Views: 497

Answers (2)

Equalsk
Equalsk

Reputation: 8194

If you want to put button1 to the right of buttonA then you can use the Left and Width properties of buttonA to work this out:

// Places button1 to the right of buttonA by 10 pixels
button1.Left = buttonA.Left + buttonA.Width + 10;

Edit:

To make sure I'm always adding to the right of the last button, I can just keep a reference to the last position that was used:

// Remember the last Left used. 
// We first set it to the Left of buttonA plus its Width.
int lastLeft = buttonA.Left + buttonA.Width;

// button1 now gets set to this plus a gap of 10 pixels
button1.Left = lastLeft + 10;
// Remember the last position
lastLeft = button1.Left + button1.Width;

// Set next button
button2.Left = lastLeft + 10;
// Remember...
lastLeft = button2.Left + button2.Width;

You could make this cleaner by wrapping some of it in a method, but I've left the verbose version for clarity.

Upvotes: 3

roemel
roemel

Reputation: 3297

You could save the total of your button Width in an integer and use it to set Left property:

private void button1_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Left = nTotalWidth;

    panel1.Controls.Add(btn);
    nTotalWidth += btn.Width;
}

This will create a new button next to the previous button everytime you hit button1.

Upvotes: 2

Related Questions