C# remove dynamic created button - c#

I am facing an issue over here. I want to remove the dynamic created button by press the X button.
The function will be user press X button, then press the button he/she want to delete, the button will be remove.
For now my program is able to create a new button but I do not know how to delete it, here is my coding, please help me , thanks very much!!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class graphtest : Form
{
public graphtest()
{
InitializeComponent();
}
private Point Origin_Cursor;
private Point Origin_Control;
private bool BtnDragging = false;
private void button1_Click(object sender, EventArgs e)
{
var b = new Button();
b.Width = 54;
b.Height = 58;
b.Image = Image.FromFile(#"C:\Users\prod01\Desktop\Mote.png");
b.Text = "";
b.Name = "button";
//b.Click += new EventHandler(b_Click);
b.MouseUp += (s, e2) => { this.BtnDragging = false; };
b.MouseDown += new MouseEventHandler(this.b_MouseDown);
b.MouseMove += new MouseEventHandler(this.b_MouseMove);
this.Controls.Add(b);
}
private void b_MouseDown(object sender, MouseEventArgs e)
{
Button ct = sender as Button;
ct.Capture = true;
this.Origin_Cursor = System.Windows.Forms.Cursor.Position;
this.Origin_Control = ct.Location;
this.BtnDragging = true;
}
private void b_MouseMove(object sender, MouseEventArgs e)
{
if (this.BtnDragging)
{
Button ct = sender as Button;
ct.Left = this.Origin_Control.X - (this.Origin_Cursor.X - Cursor.Position.X);
ct.Top = this.Origin_Control.Y - (this.Origin_Cursor.Y - Cursor.Position.Y);
}
}
private void graphtest_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
for (int ix = this.Controls.Count - 1; ix >= 0; ix--)
{
if (this.Controls[ix] is Button) this.Controls[ix].Dispose();
}
}
}
}

Here is how you can do that
//a list where you save all the buttons created
List<Button> buttonsAdded = new List<Button>();
private void button2_Click(object sender, EventArgs e)
{
Button myText = new Button();
myText.Tag = counter;
myText.Location = new Point(x2,y2);
myText.Text = Convert.ToString(textBox3.Text);
this.Controls.Add(myText);
//add reference of the button to the list
buttonsAdded.Insert(0, myText);
}
//atach this to a button removing the other buttons
private void removingButton_Click(object sender, EventArgs e)
{
if (buttonsAdded.Count > 0)
{
Button buttonToRemove = buttonsAdded[0];
buttonsAdded.Remove(buttonToRemove);
this.Controls.Remove(buttonToRemove);
}
}
Ref :- how to delete a button run time?

Related

Slow dynamic button add/remove in C#

I’am switching between buttons by adding/removing them dynamically. After 20 switches the whole application starts to be more and more slow.
It seem’s It is related to function Dispose(). When I use it the problem become worst. You can see how I used it in pasted code.
I’am using Visual Studio 2010 Express.
Any idea what I’am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Tracker
{
public partial class Tracker : Form
{
Button New_Trace = new Button();
Button Continue_Trace = new Button();
Button Save_Trace = new Button();
Button New_Point = new Button();
Button Exit_Trace = new Button();
public Tracker()
{
InitializeComponent();
Init_Menu1();
}
public void Init_Menu1()
{
New_Trace.Left = 20;
New_Trace.Top = 40;
New_Trace.Text = "New Trace";
this.New_Trace.Click += new System.EventHandler(this.New_Trace_Click);
this.Controls.Add(New_Trace);
Continue_Trace.Left = 100;
Continue_Trace.Top = 40;
Continue_Trace.Text = "Cont. Trace";
this.Continue_Trace.Click += new System.EventHandler(this.Continue_Trace_Click);
this.Controls.Add(Continue_Trace);
Save_Trace.Left = 180;
Save_Trace.Top = 40;
Save_Trace.Text = "Save Trace";
this.Save_Trace.Click += new System.EventHandler(this.Save_Trace_Click);
this.Controls.Add(Save_Trace);
}
public void Init_Menu2()
{
New_Point.Left = 20;
New_Point.Top = 40;
New_Point.Text = "New Point";
this.New_Point.Click += new System.EventHandler(this.New_Point_Click);
this.Controls.Add(New_Point);
Exit_Trace.Left = 180;
Exit_Trace.Top = 40;
Exit_Trace.Text = "Exit";
this.Exit_Trace.Click += new System.EventHandler(this.Exit_Trace_Click);
this.Controls.Add(Exit_Trace);
}
public void remove_Menu1()
{
if (this.Controls.Contains(New_Trace))
{
// this.New_Trace.Click -= new System.EventHandler(this.New_Trace_Click);
this.Controls.Remove(New_Trace);
//New_Trace.Dispose();
}
if (this.Controls.Contains(Continue_Trace))
{
// this.Continue_Trace.Click -= new System.EventHandler(this.Continue_Trace_Click);
this.Controls.Remove(Continue_Trace);
//Continue_Trace.Dispose();
}
if (this.Controls.Contains(Save_Trace))
{
// this.Save_Trace.Click -= new System.EventHandler(this.Save_Trace_Click);
this.Controls.Remove(Save_Trace);
//Save_Trace.Dispose();
}
}
public void remove_Menu2()
{
if (this.Controls.Contains(New_Point))
{
//this.New_Point.Click -= new System.EventHandler(this.New_Point_Click);
this.Controls.Remove(New_Point);
//New_Point.Dispose();
}
if (this.Controls.Contains(Exit_Trace))
{
//this.Exit_Trace.Click -= new System.EventHandler(this.Exit_Trace_Click);
this.Controls.Remove(Exit_Trace);
//Exit_Trace.Dispose();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void New_Trace_Click(object sender, EventArgs e)
{
remove_Menu1();
Init_Menu2();
}
private void Continue_Trace_Click(object sender, EventArgs e)
{
}
private void Save_Trace_Click(object sender, EventArgs e)
{
}
private void New_Point_Click(object sender, EventArgs e)
{
}
private void Exit_Trace_Click(object sender, EventArgs e)
{
remove_Menu2();
Init_Menu1();
}
}
}
Try changing visible of button to false/true instead of deleting and recreating it.
button.Visible = true; //set visible to visible
button.Visible = false; //set visible to invisible
button.Visible = !(button.Visible); //set visible to visible if button was invisible or to invisible, if button was Visible
Also In VS 2015 you have profiling tools, which can help you (but I'm not sure If they're in VS 2010 too)
Please, mark my answer as correct, if I helped you :D

c# button click on new form takes long time to load

i have a button click to pop up a new form, and it is taking a while to load up. the following is my
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CashPOS
{
public partial class SubItems : Form
{
CashSales cashSalesForm;
List<string> itemList= new List<String>();
public SubItems()
{
InitializeComponent();
addItemToList();
getMainFormInfo();
}
private void getMainFormInfo()
{
cashSalesForm = new CashSales();
createItemBtn(itemList, subItemPanel, itemBtnClicked);
}
private void addItemToList()
{
itemList.Add("abc12");
itemList.Add("abc13");
itemList.Add("abc14");
itemList.Add("abc15");
itemList.Add("abc16");
itemList.Add("abc17");
itemList.Add("abc18");
itemList.Add("abc19");
itemList.Add("abc20");
itemList.Add("abc21");
itemList.Add("abc22");
itemList.Add("abc23");
itemList.Add("abc24");
itemList.Add("abc25");
itemList.Add("abc26");
itemList.Add("abc27");
itemList.Add("abc28");
itemList.Add("abc29");
itemList.Add("abc30");
itemList.Add("abc31");
itemList.Add("abc32");
itemList.Add("abc33");
itemList.Add("abc34");
itemList.Add("abc35");
itemList.Add("abc36");
itemList.Add("abc37");
itemList.Add("abc38");
itemList.Add("abc39");
}
protected void itemBtnClicked(object sender, EventArgs e)
{
float unitPrice = 0.0f;
Button btn = sender as Button;
string itemSelected = btn.Text;
}
public void createItemBtn(List<String> itemList, Control panel, EventHandler handler)
{
for (int i = 0; i < itemList.Count; i++)
{
Button newButton = new Button();
newButton.Width = 203;
newButton.Height = 132;
newButton.AutoSize = false;
newButton.Name = "newBtn" + i;
newButton.Text = itemList[i].ToString();
// btnList.Add(newButton);
panel.Controls.Add(newButton);
}
}
}
}
this is the form that open from the following button click event
protected void itemBtnClicked(object sender, EventArgs e)
{
Button btn = sender as Button;
string itemSelected = btn.Text;
SubItems sub = new SubItems();
sub.Show();
}
i am not sure if the createItemBtn is delaying it by alot, because when I remove this function, it would open the form instantly, but with this function, it takes around 1.5 second to open the form. Is there a better way to reduce the time for this?

Button "clear" on a TextBox line appears only once

I managed to get a clear button on a TextBox line with little code. This deletes the corresponding line and itself when clicking. But the button appears only once. It should be generated with each click on each additional line. Can someone help me there? Many Thanks.
Is WinForm VS2010 C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Daten_zu_TextBox_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn";
btn1.Click += new EventHandler(btn1_Click);
btn1.Size = new Size(18, 18);
btn1.Text = "X";
btn1.ForeColor = Color.Red;
textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline1");
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
void btn1_Click(object sender, EventArgs e)
{
textBox1.Controls.Clear();
textBox1.Text = textBox1.Text.Remove(1, textBox1.Lines[0].Length + 0 );
textBox1.Text = textBox1.Text.Remove(0, textBox1.Lines[0].Length + 0);
}
}
}
private int ButtonCount2 = 0;
private int Btn2Y = 18;
private void button2_Click(object sender, EventArgs e)
{
Button btn2 = new Button();
btn2.Name = "btn2" + ButtonCount2;
btn2.Click += new EventHandler(btn2_Click);
btn2.Size = new Size(18, 18);
btn2.Location = new Point(1, Btn2Y * ButtonCount2);
ButtonCount2++;
btn2.Text = "X";
btn2.ForeColor = Color.Red;
textBox2.Controls.Add(btn2);
string sent = ("\t" + "Testline" + ButtonCount2);
textBox2.AppendText(sent);
textBox2.AppendText(Environment.NewLine);
}
void btn2_Click(object sender, EventArgs e)
{
var bt2 = sender as Button;
var bt2Id = textBox2.Controls.IndexOf(bt2);
textBox2.Controls.Remove(bt2);
var lines = textBox2.Text.Replace("\r\n", "\n").Split('\n').ToList();
lines.RemoveAt(bt2Id);
textBox2.Text = string.Join("\r\n", lines);
foreach (Button btn2 in textBox2.Controls)
{
var Id2 = int.Parse(btn2.Name.Replace("btn2", ""));
if (Id2 > bt2Id)
{
var b2 = textBox2.Controls.Find(btn2.Name, false)[0];
var loc2 = btn2.Location;
b2.Location = new Point(loc2.X, loc2.Y - Btn2Y);
}
}
ButtonCount2--;
}
The second button looks like this.
You're putting all the X buttons on the same place, on top of textbox. Implement some logic that increases Y location of your button. That can be something like this:
//... your code here ...
btn1.ForeColor = Color.Red;
//increase Y
// for each control that is inside of textBox,
// lower your newly created button by count * 18
// so that btn1.Top will be 0, 18, 36 etc...
btn1.Top = textBox1.Controls.Count * 18;
textBox1.Controls.Add(btn1);
also, as WPFUser noticed, on click on X button, you're removing all the X buttons. I'm guessing you should remove last, bottom one
EDIT 2. Each button should remove its corresponding line, like this (didn't test it :))
void btn1_Click(object sender, EventArgs e)
{
//remove right line
text1.Text = text1.Lines[text1.Controls.IndexOf((Control)sender)].Remove(0);
//remove button
text1.Controls.Remove(text1.Controls.OfType<Button>().Last());
}
#jadolo ,Your code is correct ,It add new button every time but every button will located at same location so those all button will not visible to you, Add assign location property of button like this,so all button are displayed correctly.
Form1.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
int i = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
void btn1_Click(object sender, EventArgs e)
{
textBox1.Controls.Clear();
textBox1.Text = textBox1.Text.Remove(1, textBox1.Lines[0].Length + 0);
textBox1.Text = textBox1.Text.Remove(0, textBox1.Lines[0].Length + 0);
}
private void button1_Click_1(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn"+i++;
btn1.Click += new EventHandler(button1_Click_1);
btn1.Size = new Size(18,18 );
btn1.Text = "X";
btn1.Location = new Point(0, i);
i += 18;
btn1.ForeColor = Color.Red;
this.textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline1");
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
}
}
Design :
Output :
I hope this will help you.
Below is tested working codes. The button will coincide with text for the textbox font size being the default 8.
private int ButtonCount = 0;
private int BtnY = 13;
private void button1_Click(object sender, EventArgs e)
{
Button btn1 = new Button();
btn1.Name = "btn" + ButtonCount;
btn1.Click += new EventHandler(btn1_Click);
btn1.Size = new Size(18, 18);
btn1.Location = new Point(1, BtnY * ButtonCount);
btn1.Tag = ButtonCount; // the last edit
ButtonCount++;
btn1.Text = "X";
btn1.ForeColor = Color.Red;
textBox1.Controls.Add(btn1);
string sent = ("\t" + "Testline" + ButtonCount);
textBox1.AppendText(sent);
textBox1.AppendText(Environment.NewLine);
}
void btn1_Click(object sender, EventArgs e)
{
var bt = sender as Button;
var btId = textBox1.Controls.IndexOf(bt);
textBox1.Controls.Remove(bt);
var lines = textBox1.Text.Replace("\r\n", "\n").Split('\n').ToList();
lines.RemoveAt(btId);
textBox1.Text = string.Join("\r\n", lines);
foreach (Button btn in textBox1.Controls)
{
//var Id = int.Parse(btn.Name.Replace("btn", "")); // the last edit
var Id = (int)btn.Tag; // the last edit
if (Id > btId)
{
var b = textBox1.Controls.Find(btn.Name, false)[0];
var loc = btn.Location;
b.Location = new Point(loc.X, loc.Y - BtnY);
}
}
ButtonCount--;
}

How to access a certain button to change the value of a certain text field (in a dynamically created controls)

i need to use a button to make a number of textboxes with related buttons each button will add 1 to the textbox (that i want to be related to it HOW?)
i have a windows form with button1 and three panels
==========================================
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace AdvancedCounter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (panel3.Controls != null)
{
var btn = panel3.Controls.Find("_B", true).First();
btn.Click += new EventHandler(Btn_Click);
}
}
int a = 0;
int counter=0;
private void button1_Click(object sender, EventArgs e)
{
counter++;
Button btn = new Button();
btn.Location = new Point(0, 100);
btn.Text = "ADD";
btn.Name ="_B";
btn.Dock = DockStyle.Left;
btn.Click += new EventHandler(Btn_Click);
TextBox txt = new TextBox();
txt.Name = "_T";
txt.Location = new Point(500, 100);
txt.Dock = DockStyle.Left;
txt.Text = a.ToString();
panel3.Controls.Add(txt);
panel3.Controls.Add(btn);
foreach (var item in panel3.Controls.Find("_B", true))
{
item.Text = "ass";
}
}
private void Btn_Click(object sender, EventArgs e)
{
// MessageBox.Show(sender.ToString());
// throw new NotImplementedException();
var txtbx= panel3.Controls.Find("_T", true).First();
var btnbx = panel3.Controls.Find("_B", true).First();
a++;
// find[1].Dispose();
txtbx.Text = a.ToString();
}
}
}
First you are giving same Name property for every TextBox and Button, you should not do that. Instead do like this for example:
btn.Name = "_B_"+ counter;
So you will have different Name for Buttons and TextBoxes. And in event handler:
private void Btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
string index = btn.Name.Split('_')[2];
string tbName = "_T_" + index;
var txtbx= panel3.Controls.Find(tbName, true).First();
a++;
txtbx.Text = a.ToString();
}

Array/String of dynamically created textBoxes in Visual Studio - C#

I created, dynamically, a number of textBoxes. The user will write input in those textBoxes and then press a button ("SAVE").
I want to save the info from those textBoxes in an array(or string). Is it possible to implement something like this: for(i = 0; i < the_number_of_textBoxes; i++) MY_ARRAY_or_MY_STRING += textBox[i].Text; //I know this isn't correct
I'm sure there should be something similar to my "way of thinking", but I can't find it.
If I would always have the same number of texboxes, lets say 2, I could implement it like this: MY_ARRAY_or_MY_STRING = textBox1.Text + textBox2.Text;, but my textBoxes are dynamicaly generated.
Here is the code I use (although I don't think it will be of need), my program has 2 Forms (Form1 is noted as frm1) - It has nothing to do with my question, but maybe it helps, idk. If you need more info about what the program does, ask away, I wont write it here, because it may be useless info.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Add MySql Library
using MySql.Data.MySqlClient;
namespace Proiect
{
public partial class Form2 : Form
{
public Form1 frm1;
public int numar_textBox = 5;
public int numar_eticheta = 5;
public int numar_groupBox = 0;
public int LastTextBoxLeft = 15;
public int LastEtichetaLeft = 15;
public int LastGroupBoxLeft = 3;
public Form2()
{
InitializeComponent();
frm1 = new Form1();
}
private void Form2_Load(object sender, EventArgs e)
{
int i;
for (i = 0; i < frm1.get_nr_coloane(); i++)
AddNewGroupBox();
}
private void Form2_Click(object sender, EventArgs e)
{
Deselect.Focus(); //Deseleceaza orice element, mutand focusul pe un label fara text
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
/*
public int verifica_spatii(TextBox New_text_box)
{
int i, k=0;
if (New_text_box.Text == "") return 1;
else
{
for (i = 0; i < New_text_box.TextLength; i++)
if (New_text_box.Text[i] != ' ')
{
return 1;
}
return 0; // are numai spatii
}
}
*/
public void On_click()
{
}
public event EventHandler Click_event;
public System.Windows.Forms.GroupBox AddNewGroupBox()
{
EventHandler handler = Click_event;
System.Windows.Forms.GroupBox grp = new System.Windows.Forms.GroupBox();
this.Controls.Add(grp);
grp.Width = 133;
grp.Height = 50;
grp.Top = 10;
grp.Left = LastGroupBoxLeft;
LastGroupBoxLeft += grp.Width;
grp.Text = frm1.get_nume_coloane()[numar_groupBox];
numar_groupBox += 1;
TextBox txt = new TextBox();
txt.Top = 20;
txt.Left = 10;
numar_textBox = numar_textBox + 1;
grp.Controls.Add(txt);
txt.Leave += textBoxGeneral_LostFocus;
/////New_text_box.Click += handler(this,);
return grp;
}
private void textBoxGeneral_LostFocus(object sender, EventArgs e)
{
//ToolStripItem item = (ToolStripItem)sender;
// MessageBox.Show(item.Text);
}
private void button1_Click(object sender, EventArgs e)
{
string valorile_de_adaugat="";
int i;
for(i=0;i<numar_groupBox-1;i++)
valorile_de_adaugat+=textBox[i]
//MySqlCommand Salveaza_in_baza_de_date = new MySqlCommand("INSERT INTO " + frm1.get_nume_tabel_selectat() + " ("+ frm1.get_unirea_coloanelor + ") VALUES(22056, 15, 2000, 2004));
}
/*
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
*/
}
}
Thank you for your time,
Vlad

Categories