hello everyone i'm new to c# and wpf programming and
i'm trying to create a dynamic menu where i have + and - buttons which affect a text box which represents quantity. so in a grid i call a class called productcard which i call in a page to fill the grid with the products.
now the problem is how can i use the click event inside of the product card class in my page where i have multiple cards.
class productcard
{
Button plus = new Button();
Button minus= new Button();
public TextBox qtyl = new TextBox();
Grid z = new Grid();
public int left;
public int top;
GroupBox yy;
public GroupBox XX { get { return this.yy; } set { this.yy = value; } }
public productcard(int left , int top )
{
this.left = left;
this.top = top;
Thickness margin = new Thickness(left, top, 0, 0);
Thickness bmar = new Thickness(0, 0, 0, 0);
plus.Height = 30;
plus.Width = 40;
plus.VerticalAlignment = VerticalAlignment.Bottom;
plus.HorizontalAlignment = HorizontalAlignment.Right;
plus.Content = "+";
plus.HorizontalContentAlignment = HorizontalAlignment.Center;
// - button
minus.Height = 30;
minus.Width = 40;
minus.VerticalAlignment = VerticalAlignment.Bottom;
minus.HorizontalAlignment = HorizontalAlignment.Left;
minus.Content = "-";
minus.HorizontalContentAlignment = HorizontalAlignment.Center;
// add the button to the grid
z.Children.Add(plus);
z.Children.Add(minus);
// creat text box
qtyl = new TextBox();
qtyl.Height = 30;
qtyl.Width = 30;
qtyl.Background = Brushes.White;
qtyl.VerticalAlignment = VerticalAlignment.Bottom;
qtyl.HorizontalAlignment = HorizontalAlignment.Center;
qtyl.Text = "0";
// add text box to the grid inside the group box
z.Children.Add(qtyl);
// creat group box
GroupBox yy = new GroupBox();
yy.Margin = margin;
yy.VerticalAlignment = VerticalAlignment.Top;
yy.HorizontalAlignment = HorizontalAlignment.Left;
yy.Content = z;
yy.Height = 150;
yy.Width = 150;
XX = yy;
// insert group box in the produc grid
}
public void plus_Click(object sender, EventArgs e)
{
// this.plus.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
MessageBox.Show(" + has been cliked");
int result=Convert.ToInt32(qtyl.Text)+1;
qtyl.Text = result.ToString();
}
private void minus_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(qtyl.Text) - 1;
qtyl.Text = result.ToString();
}
}
You can make a handler for your button like this:
Button myButton=new Button();
myButton.Click += delegate(object sender, RoutedEventArgs e) {
//handle event
};
I hope this helps.
Reza is correct in how to write more code for a Button generated in code.
However, I would give you a word of warning that this is not proper WPF usage of MVVM and you might be putting yourself down a path for trouble later.
I would suggest having your view's buttons bind to an ICommand that can be defined in a ViewModel that will handle doing the logic for your text update.
As you mentioned, you're having different view controls represent the data based on your button press. You're currently surviving as the view's are directly updating each other (THIS IS BAD).
The moment you want to represent this data in other views, say you want your button to update 5 labels in 3 different layouts in 2 windows, you're going to have unmaintainable references in your views.
If you have the ViewModel get a command from your view bound to the button, you can have the command logic update the property in the ViewModel that multiple views can be bound to and update them all at the same time via INotifyPropertyChanged.
Not to mention, ICommand can also let you disable buttons cleanly from being clicked.
Consider taking an hour to check out this tutorial to see the separation of View and ViewModel. What you're doing now looks like it's setting you up for a world of hurt later...
Related
I wish to load multiple groupboxes in the windows form application using a button_click event.
A groupbox should appear in the form each time the button is clicked.
Expected output.
I am having trouble making the location of the groupbox dynamic, as the second groupbox should be some distance away from the first groupbox. I thought of manually calculating the coordinates and using an array of points for the location, but I feel that there should be a better a way to go about it.
I have defined 'int count=0' variable to count the number of times the button is clicked. Based on that I am naming the new groupbox. But I think there is some problem in the logic used in the count++ line. It is not going after 1. Therefore I am only getting one groupbox "groupBox1". Nothing happens when I click the button again.
I appreciate your help.
Thank you
int count=0;
private GroupBox GetGroupBox(int a)
{
GroupBox groupBox = new GroupBox();
groupBox.Text = "groupBox"+(a.ToString());
groupBox.Width= 200;
groupBox.Height= 200;
groupBox.Location = new Point(50,400);
return groupBox;
}
private void button1_Click(object sender, EventArgs e)
{
count++;
this.Controls.Add(GetGroupBox(count));
}
Your question states these objectives:
Dynamically add a GroupBox based on an event (like button click).
Assign the new GroupBox location.
Pad the location with "some distance away".
You say you "feel that there should be a better a way to go about it" and there is!
Try experimenting with a FlowLayoutPanel which handles all three of these by its nature.
Here's the code I used to add and remove instances of CustomGroupBox. This is a UserControl that I added to my project, but this will work with any type of control.)
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
numericUpDownGroupboxes.ValueChanged += onGroupBoxCountChanged;
foreach (var radio in Controls.OfType<RadioButton>())
{
radio.CheckedChanged += onFlowLayoutDirectionChanged;
}
}
When the numeric up-down changes, compare the expected number of groupboxes to the current count. Alternatively, you can continue to use a button click and go straight to flowLayoutPanel.Controls.Add(...).
private void onGroupBoxCountChanged(object sender, EventArgs e)
{
// Need an int for comparison.
int
countIs = flowLayoutPanel.Controls.OfType<CustomGroupBox>().Count(),
countShouldBe = (int)numericUpDownGroupboxes.Value;
switch(countIs.CompareTo(countShouldBe))
{
case -1:
flowLayoutPanel.Controls.Add(
new CustomGroupBox
{
Name = $"groupBox{countShouldBe}",
Text = $"GroupBox {countShouldBe}",
Size = new Size(300, 150),
Margin = new Padding(10),
BackColor = Color.White,
});
break;
case 1:
Control last = flowLayoutPanel.Controls.OfType<CustomGroupBox>().Last();
flowLayoutPanel.Controls.Remove(last);
break;
}
}
The direction of the flow can also be specified.
private void onFlowLayoutDirectionChanged(object sender, EventArgs e)
{
if(radioButtonHorizontal.Checked)
{
flowLayoutPanel.FlowDirection = FlowDirection.LeftToRight;
}
else
{
flowLayoutPanel.FlowDirection = FlowDirection.TopDown;
}
}
}
Since you want to create boxes from left to right you should adjust Left: say, 1st box should have Left = 50, 2nd Left = 270, 3d Left = 490 etc.
Code:
const int deltaX = 20;
...
//TODO: check do you really want Top = 400, not, say, 20?
groupBox.Location = new Point(50 + (a - 1) * (groupBox.Width + deltaX), 400);
...
Simplified implementation can be
int count = 0;
// Let's rename the method: we actually create GroupBox, not get existing
private GroupBox CreateGroupBox(int index) => new GroupBox() {
Text = $"groupBox{index}",
Size = new Size(200, 200),
Location = new Point(50 + (index - 1) * (20 + 200), 400),
Parent = this, // Instead of Controls.Add()
};
private void button1_Click(object sender, EventArgs e) {
CreateGroupBox(++count);
}
I'm creating a ComboBox control using ToolStripControlHost and ToolStripDropDown that can host any kind of control in the DropDown window. For example, the DropDown window might display a listview or treeview or even another usercontrol.
I'm posting a simplified code below where dropdown host a usercontrol with a listview and a button like this:
The problem occurs when the control is positioned at the bottom of the screen in such a way that the dropdown window will extrapolate the lower boundary of the screen. When this occurs, the dropdown ends up hiding the control.
In this case, I'd like to fix the _dropDown.Show method call to show dropdown window as follows:
To repeat the problem, just run the code below and drag the window to the bottom of the screen and open the dropdown.
using System;
using System.Windows.Forms;
public class CustomComboBox : UserControl
{
ToolStripDropDown _dropDown;
public CustomComboBox()
{
var textbox = new TextBox();
textbox.Location = new System.Drawing.Point(0, 0);
textbox.Size = new System.Drawing.Size(this.Width - 22, 20);
textbox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
this.Controls.Add(textbox);
var button = new Button();
button.Location = new System.Drawing.Point(this.Width - 22, -1);
button.Size = new System.Drawing.Size(22, 22);
button.Text = "\u2BC6";
button.Anchor = AnchorStyles.Right | AnchorStyles.Top;
button.Click += new System.EventHandler(this.Button_Click);
this.Controls.Add(button);
var dropDownControl = new DropDownControlTest();
var controlHost = new ToolStripControlHost(dropDownControl);
_dropDown = new ToolStripDropDown();
_dropDown.AutoSize = true;
_dropDown.Items.Add(controlHost);
}
void Button_Click(object sender, EventArgs e)
{
_dropDown.Show(this, 0, this.Height);
}
}
public class DropDownControlTest : UserControl
{
public DropDownControlTest()
{
var listview = new ListView();
listview.Location = new System.Drawing.Point(3, 1);
listview.Size = new System.Drawing.Size(400,300);
listview.View = View.Details;
listview.Columns.Add("Col 1",100);
listview.Columns.Add("Col 2",100);
this.Controls.Add(listview);
var button = new Button();
button.Location = new System.Drawing.Point(3, 305);
button.Text = "More...";
this.Controls.Add(button);
}
}
public class Form1 : Form
{
private static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public Form1 ()
{
CustomComboBox ccBox = new CustomComboBox();
ccBox.Location = new System.Drawing.Point(10, 10);
ccBox.Height = 20;
this.Text = "Test CustomComboBox";
this.Controls.Add(ccBox);
}
}
You can use the ToolStripDropDown.Show Method (Control, Point, ToolStripDropDownDirection) overload to control the drop direction. The code will need to perform bounds checking to decide whether to place the dropdown above or below the textbox.
The following is a simplistic method for doing the bounds checking and was only tested on a single screen configuration.
First, make textbox a class level variable.
private TextBox textbox;
public CustomComboBox()
{
//var textbox = new TextBox();
textbox = new TextBox();
The display logic is as follows.
void Button_Click(object sender, EventArgs e)
{
Point textBoxScreenLocation = textbox.PointToScreen(textbox.Location);
// try to position _dropDown below textbox
Point pt = textBoxScreenLocation;
pt.Offset(0, textbox.Height);
// determine if it will fit on the screen below the textbox
Size dropdownSize = _dropDown.GetPreferredSize(Size.Empty);
Rectangle dropdownBounds = new Rectangle(pt, dropdownSize);
if (dropdownBounds.Bottom <= Screen.GetWorkingArea(dropdownBounds).Bottom)
{ // show below
_dropDown.Show(pt, ToolStripDropDownDirection.BelowRight);
}
else
{ // show above
_dropDown.Show(textBoxScreenLocation, ToolStripDropDownDirection.AboveRight);
}
}
}
I can not comment that is why I am answering your question. You can use the reflection and then re-position you control. I have found a custom combobox control same as you developed. Please check this. At least, you will get some idea what you need to do.
I have searched everywhere, but the procedure are so painful. How to put multiple RadioButton into a panel programatically without using toolbox. I'm using WinForms. After several suggestion/s, I still can't add the radiobuttons inside the panel.
public partial class Form1 : Form
{
RadioButton[] RadioButton_WallFirstStorey_Yes = new RadioButton[100];
RadioButton[] RadioButton_WallFirstStorey_No = new RadioButton[100];
Panel[] Panel_WallFirstStorey = new Panel[100];
int CheckBoxWidth = 100;
public Form1()
{
InitializeComponent();
//code
//procedure
}
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
Controls.Add(RadioButtonX);
}
private void InitializePanel_Wall(Panel PanelX)
{
PanelX.BackColor = Color.PaleTurquoise;
PanelX.BorderStyle = BorderStyle.Fixed3D;
PanelX.BringToFront();
Controls.Add(PanelX);
}
private void MyProcedure()
{
int i;
for (i = 1; i <= 100; i++)
{
Panel_WallFirstStorey[i] = new Panel();
InitializePanel_Wall(Panel_WallFirstStorey[i]);
Panel_WallFirstStorey[i].Location = new Point(Label_SeparatorLineVertical[ColumnMinimum + i].Location.X, Label_SeparatorLineHorizontal[RowMinimum + i].Location.Y);
Panel_WallFirstStorey[i].Width = (Label_SeparatorLineVertical[ColumnMaximum].Location.X - Label_SeparatorLineVertical[ColumnMinimum].Location.X) / (ColumnMaximum - ColumnMinimum);
Panel_WallFirstStorey[i].Height = CheckBoxWidth;
Panel_WallFirstStorey[i].SendToBack();
}
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);//I add this stuff
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);//I add this stuff
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
RadioButton_WallFirstStorey_Yes[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_No[i].Font = SystemFonts.DefaultFont;
RadioButton_WallFirstStorey_Yes[i].BringToFront();
RadioButton_WallFirstStorey_No[i].BringToFront();
}
}
}
Wow, your code is wrong in so many ways.... It creates controls over and over whenever a panel is painted, but it never really adds them anywere.
To add a radio button b to a panel p, it would be enough to do this:
RadioButton b = new RadioButton();
// Set properties for button here (text, location, handlers, etc.)
p.Controls.Add(b);
I'd try the following procedure instead of yours:
private void MyProcedure()
{
for (i = 1; i <= 100; i++)
{
RadioButton_WallFirstStorey_Yes[i] = new RadioButton();
RadioButton_WallFirstStorey_No[i] = new RadioButton();
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_Yes[i]);
InitializeRadioButton_Wall(RadioButton_WallFirstStorey_No[i]);
RadioButton_WallFirstStorey_Yes[i].Text = "Yes";
RadioButton_WallFirstStorey_No[i].Text = "No";
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width * 2 / 3, Panel_WallFirstStorey[i].Location.Y);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_Yes[i]);
Panel_WallFirstStorey[i].Controls.Add(RadioButton_WallFirstStorey_No[i]);
}
}
The following code indicates you're still doing it wrong, adding the radio buttons to the form itself, but positioning them as if you had added them to the panel:
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Location.X + Panel_WallFirstStorey[i].Width / 3, Panel_WallFirstStorey[i].Location.Y);
If you added the button to the panel, it would most probably be invisible because it is outside the panel. If you added the button to the panel, you'd have to use coordinates relative to the panel's client area.
RadioButton_WallFirstStorey_Yes[i].Location = new Point(Panel_WallFirstStorey[i].Width / 3, 0);
RadioButton_WallFirstStorey_No[i].Location = new Point(Panel_WallFirstStorey[i].Width * 2 / 3, 0);
Your update code shows clearly where your error is:
private void InitializeRadioButton_Wall(RadioButton RadioButtonX)
{
RadioButtonX.AutoSize = true;
RadioButtonX.Font = SystemFonts.DefaultFont;
RadioButtonX.BackColor = Color.Transparent;
// REMOVE THIS LINE!!
Controls.Add(RadioButtonX);
}
The last line adds the radio button to the form. As we've been telling you all the time. Remove the line I marked above. Then, the radio buttons will be added to the panels only. After that it is a question of getting the positions right.
You can for example create a panel (or a GroupBox) and in a loop add the RadioButtons.
It should work like with any other control in Winforms.
// Adds 10 Radiobuttons with the name "Radio <number>"
public Form1()
{
InitializeComponent();
for (int n = 0; n < 10; n++)
{
// First instantiate a new RadioButton.
RadioButton button = new RadioButton();
// Now the name of the button.
button.Text = "Radio" + n;
// Dock the button to the top of the GroupBox (to put them in order)
button.Dock = DockStyle.Top;
// Add the button to the GroupBox.
this.groupBoxRadio.Controls.Add(button);
}
}
Your question is not very clear, and no code for context, but you should be able to create an instance of a new radiobutton and add it to the controls of the panel.
It may also be best to use RadioButtonList like Harvey has mentioned, but to try to answer your question:
var someRadioBtn = new RadioButton();
// set properties...
pnlMyPanel.Controls.Add(someRadioBtn);
I create buttons in my application by:
List<Button> btnslist = new List<Button>();
for (int i = 0; i < nbrofbtns; i++)
{
Button newButton = new Button();
btnslist.Add(newButton);
this.Controls.Add(newButton);
newButton.Width = btnsidelength;
newButton.Height = btnsidelength;
newButton.Top = btnsidelength
* Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
newButton.Left = btnsidelength
* Convert.ToInt32(
Math.Floor(Convert.ToDouble(i))
- Math.Floor((Convert.ToDouble(i))
/ (Form2.puzzlesize)) * (Form2.puzzlesize));
newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
newButton.Tag = (i+1).ToString();
newButton.Click += new EventHandler(Any_Button_Click);
Then I have a method for when any of the buttons are clicked.
void Any_Button_Click(object sender, EventArgs e)
{
//the variable b has all the insformation that the single button had itself.
Button b = (Button)sender;
if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
{
MessageBox.Show(b.Tag.ToString());
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
btnslist[Convert.ToInt32(b.Tag)].BackgroundImage =
Lights_out_.Properties.Resources.LightsOutWhite;
MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
}
else
{
MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = "
+ b.BackgroundImage.ToString());
}
}
How do I change the data in the actual button (then said button is clicked)? I want specificly to change the backgroundimage. How could I do this?? (I also need to change the backgroundimage of some other buttons created by the code.)
The sender object is the button:
Button b = (Button)sender;
... so you should be able to change properties on it directly:
b.WhateverPropsToChange = yourSetting;
PS: I don't think this is necessary, but if the button is not updated directly, you might try to using b.Refresh() to let it know something has changed.
You're handling Click event of every button you've created - and sender in Any_Button_Click is actually the button was clicked.
So just change b.BackgroundImage to whatever you need.
I have a problem in my C# file. I have to create 6 buttons programmatically on specific location. but my for loop doesn't work..
just one button shows and not all the buttons.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
//using System.Array;
namespace AimPass
{
public partial class main : PhoneApplicationPage
{
public main()
{
InitializeComponent();
}
private void newbutton(object sender, RoutedEventArgs e)
{
// How many buttons do you want ?
int NumOfButtons = 6;
// X Location of each created button in the panel
int loc = 20;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
btn.Name = "Btn-" + i.ToString();
btn.Size= new Size(50, 20);
btn.Tag = i;
btn.Content = "Browse-" + i.ToString();
btn.location = new Point(5, loc);
}
//Add Click event Handler for each created button
btn.Click += Buttons_Click;
loc += 20;
// Add the created btn to grid
grid.Children.Add(btn);
}
}
}
}
there are 2,3 errors comes..
using System.Windows.Controls.Buttons does not contain a definition of location and size...???
btn.Click += Buttons_Click; does not exist in current context..
And loop is not working..Just one buttons comes except 6 buttons..
I wanna add button on a specific location..So these errors comes to my requirement..
Thanx in advance for solving this..:)
Some time before i have right this ..so take a look you will get what you have read..
it is little bit lengthy but i think it will help you to understand what are you looking for..You can add Row and add button to it in a loop simultaneously but little more is always good..
this is your solution..for your case..but i think you going on wrong way..
private void newbutton()
{
// How many buttons do you want ?
int NumOfButtons = 6;
// X Location of each created button in the panel
StackPanel stkpanel = new StackPanel();
stkpanel.Orientation = Orientation.Horizontal;
int loc = 20;
for (int i = 1; i <= NumOfButtons; i++)
{
Button btn = new Button();
{
btn.Name = "Btn-" + i.ToString();
btn.Height = 20;
btn.Width = 50;
btn.Foreground = new SolidColorBrush(Colors.White);
btn.Content = "btnnum" + i.ToString();
btn.Tag = i;
btn.Content = "Browse-" + i.ToString();
btn.Margin = new Thickness(5 + loc, 5, 5, 5);
btn.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Top;
}
//Add Click event Handler for each created button
btn.Click += btn_Click;
loc += 20;
// Add the created btn to grid
stkpanel.Children.Add(btn);
}
grid.Children.Add(stkpanel);
}
void btn_Click(object sender, RoutedEventArgs e)
{
// throw new NotImplementedException();
}
so..it is better you tried something in some sample projects..what i want to canvey to you..
And as the previous answer says button does not contain properties like loc etc that you want to set..for that Margin is thr..and For Size Height and Width are there..and important thing is..first you write Xaml for what you want to achieve and try to set the properties that you set in xaml during in run time in new project..it will definitely tell you how things work..
Grid grdbooltype = new Grid();
grdbooltype.Name = "Grid_" + keybooltype;
grdbooltype.Margin = new Thickness(0, 20, 20, 0);
grdbooltype.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
grdbooltype.RowDefinitions.Add(new RowDefinition());
TextBlock objtextblock = new TextBlock();
objtextblock.Text = "Select Image";
objtextblock.FontSize = 15;
grdbooltype.Children.Add(objtextblock);
Grid.SetRow(objtextblock, 0);
Grid grdtoggleswitch = new Grid();
grdtoggleswitch.Name = headername;
grdtoggleswitch.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
grdtoggleswitch.ColumnDefinitions.Add(new ColumnDefinition());
TextBlock txtblktoggleswitchleft = new TextBlock();
txtblktoggleswitchleft.FontSize = 15;
txtblktoggleswitchleft.VerticalAlignment = VerticalAlignment.Center;
txtblktoggleswitchleft.Text = headername;
Grid.SetColumn(txtblktoggleswitchleft, 0);
ToggleSwitch toggleswitch = new ToggleSwitch();
toggleswitch.Name = key;
toggleswitch.HorizontalAlignment = HorizontalAlignment.Right;
toggleswitch.Padding = new Thickness(0);
toggleswitch.IsOn = defaultvalue;
toggleswitch.Margin = new Thickness(0, 0, 0, 0);
toggleswitch.OnContent = "On";
toggleswitch.OffContent = "Off";
Grid.SetColumn(toggleswitch, 1);
grdtoggleswitch.Children.Add(txtblktoggleswitchleft);
grdtoggleswitch.Children.Add(toggleswitch);
Grid.SetRow(grdtoggleswitch, 1);
grdbooltype.Children.Add(grdtoggleswitch);
Well, first of all, buttons in Windows Phone don't have size nor location. Why would you think that they do? Instead of Size, you have two properties: Width and Height.
As for location, XAML doesn't work that way. Grid is a special kind of control that creates a layout and you define how many columns and rows you want in your grid. Then you place controls inside individual cells or you can make controls span cells.
Maybe you should learn a bit about XAML first, here is a good starting point: Layout for Windows Phone.
--
EDIT: Adding sample code for placing a button in first row and first column. Note that you have to define grid and column definition either in XAML or code.
grid.Children.Add(btn);
Grid.SetRow(btn, 0);
Grid.SetColumn(btn, 0);