how can i store value in button at runtime? - c#

I have a problem i have some dynamic button.and i want to store integer value in that.
and get that value on that click event of that button how can i achieve it
thanks in advance
shashank
DataView dv = new DataView(dtCat, "PK_CATEGORY_ID IN(" + categoryIds.ToString() + "0)", "PK_CATEGORY_ID", DataViewRowState.CurrentRows);
foreach (DataRowView rr in dv)
{
//MessageBox.Show(rr[0].ToString() + "------------" + rr[1].ToString());
Button b2 = new Button();
//b2.Name = rr[0].ToString();
b2.Name = "";
b2.Height = 200;
b2.Width = 200;
b2.Margin = new Thickness(0, -100, 0, 0);
b2.HorizontalAlignment = HorizontalAlignment.Left;
b2.Content = rr[1].ToString();
b2.Background = System.Windows.Media.Brushes.Pink;
b2.Click += new RoutedEventHandler(b2_Click);
btncanvas.Children.Add(b2);
Canvas.SetLeft(b2, b2.Width * i);
i = i + 1;
MessageBox.Show(rr[0].ToString());
b2.Tag = rr[0].ToString();
}
void b2_Click(object sender, RoutedEventArgs e)
{
Button clicked = (Button)sender;
categoryname = clicked.Name;
}

The Tag property is probably what you want.
You are already using it in your example, but just have:
b2.Tag = integerValue;
Then in your click handler use Convert.ToInt32(object) method to get the integer value back:
int retrievedValue = Convert.ToInt32(clicked.Tag);

Related

Check which Radio Button is checked in C#, with dynamically created radiobuttons

I can't find any solution or hint on this problem. Problem described after this code.
I must create one picturebox and radiobutton for every folder found on a specific path:
{
InitializeComponent();
string pathtocircuits = "../../tracks";
string[] allfiles = Directory.GetDirectories(pathtocircuits, "*.*", SearchOption.TopDirectoryOnly);
int imgx = 387;
int imgy = 153;
int radx = 428;
int rady = 259;
String track = "";
String pici = "";
String pic = "pictureBox";
String rad = "radiobutton";
String radr = "";
String picr = "";
foreach (String file in allfiles)
{
track = Path.GetFileName(file);
pici = "../../tracks/" + track + "/p_" + track + ".png";
picr = pic + element.ToString();
radr = rad + element.ToString();
PictureBox pb = new PictureBox();
pb.Location = new System.Drawing.Point(imgx, imgy); ;
pb.Image = Image.FromFile(pici);
pb.Width = 100;
pb.Height = 100;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Name = picr;
Controls.Add(pb);
RadioButton rdo = new RadioButton();
rdo.Name = radr;
rdo.Text = "";
rdo.Tag = track;
rdo.Location = new Point(radx, rady);
this.Controls.Add(rdo);
element += 1;
imgx += 110;
radx += 110;
}
}
With this part I get to create the elements I need (it works).
My problem is when I press a button to reach Form2. How can I check which radiobutton is selected and store its Tag value in a String?
for(int i = 0; i<element; i++)
{
if( ??? .Checked == true )
{
globalstring = ??? .Tag;
}
}
If I try to use the name of a created radiobutton instead of a ??? it gives me an error like 'element ??? does not have a Checked or Tag attribute'
Add method below
Add to For loop : rdo.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
RadioButton button = sender as RadioButton;
string name = button.Text;
}
RadioButtons as any other control are stored in the Controls collection of their container. If you add them directly to the form you can retrieve them using this code.
protected void Button1_Click(object sender, EventArgs e)
{
var radio = this.Controls.OfType<RadioButton>().FirstOrDefault(x => x.Checked);
if(radio != null)
{
string tag = radio.Tag.ToString();
.....
// Form2 = new Form2(tag);
}
}
The radiobuttons are added to a same group by default, so you can get the checked radiobutton as followed.
List<RadioButton> radioButtons = this.Controls.OfType<RadioButton>().ToList();
RadioButton rb = radioButtons
.Where(r => r.Checked)
.Single();
string tag = rb.Tag.ToString();

How to create event from control's that not yet create?

My program is the create datagridview program that user can create dynamic columns like row,column,panel(panel is quantity of the panel) so user can mark it too,
as I know I can mark the cell with CurrentCell.Style.BackColor
when I generate datagridview I have assign name of it But !!!! it cant use the new datagridvieweventhandler command so I cant do any thing with each datagridview
so this is my Datagridview Generate Code
string[] Panelname = { "One","Two","Three","Four","Five"};
for(i=0;i<Panelname.length;i++){
Generate(Panelname[i],a,b)}
DataGridView generate(string name,int columns,int rows)
{
int i;
Control Gen;
Control LB;
LB = new Label();
LB.Text = "Panel : "+name;
LB.Location = new Point(50 + 120 / (c - 1) + 900 / c , 315);
LB.BackColor = Color.Silver;
Gen = new DataGridView();
Gen.Name = name.ToString();
Gen.Size = new Size(900/c,300 );
Gen.Location = new Point(120 / (c ) + 900 / c, 0);
DataGridView CH = (DataGridView)Gen;
CH.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
CH.CellClick += new DataGridViewCellEventHandler(CH_CellClick);
CH.Location = new Point(0+locate, 0);
for (i = 1; i <= columns; i++)
{
CH.Columns.Add("", "");
}
for (i = 1; i < rows; i++)
{
CH.Rows.Add("", "");
}
dataGridView1.Controls.Add(LB);
dataGridView1.Controls.Add(CH);
return null;
}
How can I create the event handler for each datagridview that I'm create it dynamicly ?
thankyou for your kind
Create your datagridview.
for (int i = 0; i < 10; i++)
{
DataGridView d = new DataGridView();
d.MouseClick += dataGridView_MouseClick;
}
Use the add handler method.
private void dataGridView_MouseClick(object sender, MouseEventArgs e)
{
// Use sender to determine which datagridview fired the event
}
The problem that I found is when I'm create datagridview in the datagridview it hard to define it what's datagridview that you're clicking so I have stuck in this problem for a while
And now I found out the way's to through out my problem now, here it is
for(i=0;i
DataGridView generate2(string name, int columns, int rows,int form)
{
Control Gen;
Control LB;
int x = 1;
int runcolumn = columns;
int runrow = rows;
int count=0;
LB = new Label();
LB.Text = "Panel : " + name;
LB.Location = new Point(50 + 120 / (c - 1) + 900 / c, 320);
LB.BackColor = Color.Silver;
Gen = new DataGridView();
Gen.Name = name.ToString();
Gen.Location = new Point(120 / (c) + 900 / c, 0);
DataGridView CH = (DataGridView)Gen;
CH.RowTemplate.Height = 290 / rows;
CH.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
CH.Size = new Size(900 / c, 300);
CH.RowHeadersWidth = 10;
CH.ColumnHeadersHeight = 10;
CH.Location = new Point(0 + locate, 0);
And********* CH.Click += new EventHandler(control_click);********* this is my hero's
private void control_click(object sender, EventArgs e)
{
if (sender is DataGridView)
{
DataGridView A = (DataGridView)sender;
textBox2.Text = A.CurrentCell.RowIndex.ToString();
textBox1.Text = A.CurrentCell.ColumnIndex.ToString();
textBox3.Text = A.Name.ToString();
}
}
in the send control click function you can find what's kind of your control and cast it , so whatever control that you click it you can set it's function now!

Dynamic button, textbox and picturebox creation

Here I am doing a project where questions are presented in images. When the project loads, "start exam" button will be present in the screen. After pressing the button, it should create a picturebox, a textbox and a button for each image from specified path. Then users has to enter the answer in a textbox which is created dynamically. After the dynamic submit button is clicked for every image, the textbox values have to be stored in the listbox. I don't know how get the values from textbox. Can anyone help me out from this?
Here is my code:
PictureBox[] pics = new PictureBox[100];
TextBox[] txts = new TextBox[100];
Button[] butns = new Button[100];
FlowLayoutPanel[] flws = new FlowLayoutPanel[100];
private void button1_Click( Object sender , EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
flws[i] = new FlowLayoutPanel();
flws[i].Name = "flw" + i;
flws[i].Location = new Point(3,brh);
flws[i].Size = new Size(317,122);
flws[i].BackColor = Color.DarkCyan;
flws[i].BorderStyle = BorderStyle.Fixed3D;
pics[i] = new PictureBox();
pics[i].Location = new Point(953, 95 + brh);
pics[i].Name = "pic" + i;
pics[i].Size = new Size(300, 75);
pics[i].ImageLocation = "C:/" + listBox1.Items[i];
flws[i].Controls.Add(pics[i]);
txts[i] = new TextBox();
txts[i].Name = "txt" + i;
txts[i].Location = new Point(953, 186 + brh);
flws[i].Controls.Add(txts[i]);
butns[i] = new Button();
butns[i].Click += new EventHandler(butns_Click);
butns[i].Text = "submit";
butns[i].Name = "but" + i;
butns[i].Location = new Point(1100, 186 + brh);
flws[i].Controls.Add(butns[i]);
flowLayoutPanel1.Controls.Add(flws[i]);
brh += 130;
}
}
private void butns_Click(object sender, EventArgs e)
{
Button butns = sender as Button;
TextBox txts = sender as TextBox;
listBox2.Items.Add("text values " + txts.Text.ToString());
}
I would create a usercontrol to combine the controls.
Search for "custom usercontrol c#"
Regards.
Try this...
private void butns_Click(object sender, EventArgs e)
{
Button butns = sender as Button;
string btnName = butns.Name;
string Id = btnName.Substring(3);
string txtName = "txt" + Id;
listBox2.Items.Add("text values " + GetValue(txtName));
}
private string GetValue(string name)
{
TextBox txt = new TextBox();
txt.Name = name;
foreach (Control ctl in this.Controls)
{
if (ctl is FlowLayoutPanel)
{
foreach (Control i in ctl.Controls)
{
if (((TextBox)i).Name == txt.Name)
{
txt = (TextBox)i;
return txt.Text;
}
}
}
}
return txt.Text;
}

When dynamically adding controls to a form only one will show

I am adding two controls dynamically during runtime, however only the control that is made first is displayed.
Here is the code:
Label tempLab = new Label();
tempLab.text = "Test Label";
MyControl.Controls.Add(tempLab);
tempLab.Location = new Point(5,5);
Button tempBut = newButton()
tempBut.text = "Test Button";
MyControl.Controls.Add(tempBut);
tempBut.Location = new Point(20,20);
Isn't copypasta so ignore syntax errors with caps.
Any ideas ?
They are being added to a groupbox. I have tried adding them to a panel or just the form and the same issue occurs. I don't need event handlers, so please don't cite that requirement.
I quickly tried your code pasting it in a windows form constructor. It runs ok, but the label is slightly overlapping the button because of its size. You may want to autosize it:
Label tempLab = new Label();
tempLab.Text = "Test Label";
tempLab.AutoSize = true;
Controls.Add(tempLab);
tempLab.Location = new Point(5,5);
Button tempBut = new Button();
tempBut.Text = "Test Button";
Controls.Add(tempBut);
tempBut.Location = new Point(20,20);
Oh, by the way. You mentioned you are using MyControl as a Panel or a GroupBox. Please ensure that you are also adding MyControl to your Controls collection.
it appears that the location does not have a Size which becomes a flat line so to speak which is not visible.. this tempBut.Location = new Point(20,20); try changing to this
this.tempBut.Location = new System.Drawing.Point(20,20);
this.tempBut.Size = new System.Drawing.Size(30, 15);
hope this helps. I am adding a array of MyTextBox into panel.
Point prevlocation = new Point(0,0);
foreach (object key in keys) //List of Objects or which make new controls
{
MyTextBoxControlArray[i] = new MyTextBoxUserControl(key); //User control but could be any control like textbox etc
MyTextBoxControlArray[i].Width = this.panel1.Width - 50;
MyTextBoxControlArray[i].AutoSize = true;
MyTextBoxControlArray[i].InfoLoad += new MyTextBoxUserControl.InfoLoadEventHandler(Form1_InfoLoad);
if (i == 0)
{
//first control
prevlocation.Y += 3;
prevlocation.X += 3;
MyTextBoxControlArray[i].Location = prevlocation;
}
else
{
//adjsuting height and width
MyTextBoxControlArray[i].Location = new System.Drawing.Point(
prevlocation.X,
prevlocation.Y + MyTextBoxControlArray[i].Height+3);
}
prevlocation = MyTextBoxControlArray[i].Location;
i++;
}
this.panel1.Controls.AddRange(MyTextBoxControlArray); //in panel i can add a array of controls , but this could be done one by one
string sql3 = "SELECT COUNT(*) from systeminfo";//counting no of element
n = dm.countelement(sql3);
int i, c = 1;
int m = 100;
for (i = 0; i < n; i++, c++)
{
sql3 = " SELECT Company_name FROM systeminfo LIMIT " + (i + 1) + " OFFSET " + i + "";
string cname = dm.getlang(sql3);
PictureBox pb = new PictureBox();
Label lb = new Label();
pb.Location = new System.Drawing.Point(m, 30 + (30 * i));
lb.Location = new System.Drawing.Point(m-30, 30 + ((30 * i)-30));
pb.Name = "p" + c;
lb.Name = "l" + c;
lb.Size = new System.Drawing.Size(100, 20);
pb.Size = new System.Drawing.Size(30, 30);
lb.Text = cname;
lb.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
lb.BackColor = Color.Transparent;
pb.ImageLocation = #"..\image\image.jpg";
pb.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picmap1_MouseDown_1);
pb.MouseMove += new System.Windows.Forms.MouseEventHandler(this.picmap1_MouseMove_1);
pb.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picmap1_MouseUp_1);
picmap1.Controls.Add(pb);
picmap1.Controls.Add(lb);
c++;
}
private void picmap1_MouseMove_1(object sender, MouseEventArgs e)
{
var c = sender as PictureBox;
if (!_dragging || null == c) return;
c.Top = e.Y + c.Top - _yPos;
c.Left = e.X + c.Left - _xPos;
foreach (Control d in picmap1.Controls)
if (d is Label)
{
d.Top = e.Y + d.Top - _yPos;
d.Left = e.X + d.Left - _xPos;
}
}
private void picmap1_MouseUp_1(object sender, MouseEventArgs e)
{
var c = sender as PictureBox;
if (null == c) return;
_dragging = false;
}
private void picmap1_MouseDown_1(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
_dragging = true;
_xPos = e.X;
_yPos = e.Y;
foreach (Control d in picmap1.Controls)
if (d is Label)
{
_xPos = e.X;
_yPos = e.Y;
}
}
this is example of dynamic add control with move on mouse drag

GUI output differs from local vs production

I am having a weird experience. I am dynamically creating a row of textboxes at runtime when the user clicks a button.
However, on my local machine the text boxes appear correctly (example
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
[TextBox1] [TextBox2] [TextBox3] [TextBox4] [TextBox5]
When I run this app on the production, the output side-by-side is:
[TextBox1][TextBox1] [TextBox2][TextBox2] [TextBox3][TextBox3] [TextBox4][TextBox4]
The output should be one row of textboxes, then a second row of 5 text boxes etc.
The code that builds the textboxes is:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dyntxtCar = new TextBox[myCount];
dyntxtMake = new TextBox[myCount];
dyntxtMileage = new TextBox[myCount];
dyntxtVIN = new TextBox[myCount];
dyntxtSLIC = new TextBox[myCount];
dyntxtPlateNumber = new TextBox[myCount];
for (i = 0; i < myCount; i += 1)
{
TextBox txtCar = new TextBox();
TextBox txtMake = new TextBox();
TextBox txtMileage = new TextBox();
TextBox txtVIN = new TextBox();
TextBox txtSLIC = new TextBox();
TextBox txtPlateNumber = new TextBox();
txtCar.ID = "txtVehCar" + i.ToString();
txtMake.ID = "txtVehMake" + i.ToString();
txtMileage.ID = "txtVehMilage" + i.ToString();
txtVIN.ID = "txtVehVIN" + i.ToString();
txtSLIC.ID = "txtVehSLIC" + i.ToString();
txtPlateNumber.ID = "txtVehPlate" + i.ToString();
//Set tabIndex values for dynamic text fields;
txtCar.TabIndex = System.Convert.ToInt16(i * 10 + 1);
txtMake.TabIndex = System.Convert.ToInt16(i * 10 + 2);
txtMileage.TabIndex = System.Convert.ToInt16(i * 10 + 3);
txtVIN.TabIndex = System.Convert.ToInt16(i * 10 + 4);
txtSLIC.TabIndex = System.Convert.ToInt16(i * 10 + 5);
txtPlateNumber.TabIndex = System.Convert.ToInt16(i * 10 + 6);
//Set maxlength for dynamic fields;
txtCar.MaxLength = System.Convert.ToInt16(7);
txtVIN.MaxLength = System.Convert.ToInt16(17);
txtSLIC.MaxLength = System.Convert.ToInt16(4);
//Set width of text boxes
txtCar.Width = System.Convert.ToInt16("65");
txtMileage.Width = System.Convert.ToInt16("50");
txtVIN.Width = System.Convert.ToInt16("220");
txtSLIC.Width = System.Convert.ToInt16("45");
//txtPlateNumber.Width = System.Convert.ToInt16("35");
phCar.Controls.Add(txtCar);
phMake.Controls.Add(txtMake);
phMileage.Controls.Add(txtMileage);
phVIN.Controls.Add(txtVIN);
phSLIC.Controls.Add(txtSLIC);
phPlateNumber.Controls.Add(txtPlateNumber);
dyntxtCar[i] = txtCar;
dyntxtMake[i] = txtMake;
dyntxtMileage[i] = txtMileage;
dyntxtVIN[i] = txtVIN;
dyntxtSLIC[i] = txtSLIC;
dyntxtPlateNumber[i] = txtPlateNumber;
LiteralControl literalBreak = new LiteralControl("<br />");
phCar.Controls.Add(literalBreak);
phMake.Controls.Add(literalBreak);
phMileage.Controls.Add(literalBreak);
phVIN.Controls.Add(literalBreak);
phSLIC.Controls.Add(literalBreak);
phPlateNumber.Controls.Add(literalBreak);
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if ((myControl != null))
{
if ((myControl.ClientID.ToString() == "btnAddTextBox"))
{
myCount = myCount + 1;
}
}
}
public static Control GetPostBackControl(Page thePage)
{
Control myControl = null;
string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
if (((ctrlName != null) & (ctrlName != string.Empty)))
{
myControl = thePage.FindControl(ctrlName);
}
else
{
foreach (string Item in thePage.Request.Form)
{
Control c = thePage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
myControl = c;
}
}
}
return myControl;
}
Anyone experience this?

Categories