I am writing a code in C# I have 2 Forms and the code creates textboxes and corresponding checkboxes dynamically. The code I wrote creates dynamic textboxes and checkboxes successfully. However, I am not able to delete the row of textboxes in a selected checkbox line.
public void CreateTextBox(int i, StringReader sr)
{
ProductForm form2 = new ProductForm();
_cb = new CheckBox[i];
form2.Visible = true;
form2.Activate();
int x = 10;
int y = 30;
int width = 100;
int height = 20;
for (int n = 0; n < i; n++)
{
String line = sr.ReadLine();
String[] line_ = line.Split(new char[] {'\t'});
String cbName = "chkBox_" + n.ToString();
_cb[n] = new CheckBox();
_cb[n].Name = cbName;
_cb[n].Location = new Point(2, y);
_cb[n].Checked = false;
form2.Controls.Add(_cb[n]);
if (line.Length > 3)
{
for (int row = 0; row < 4; row++)
{
String name = "txtBox_" + row.ToString();
TextBox tb = new TextBox();
tb.Name = name;
tb.Text = line_[row].ToString();
tb.Location = new Point(x, y);
tb.Height = height;
if (row == 1)
{
tb.Width = width * row;
}
if (row == 3)
{
tb.Width = width * 5;
}
else
{
tb.Width = width - 20;
}
x += 10 + width;
form2.Controls.Add(tb);
}
}
x = 10;
y += 25;
}
}
private void DeleteTextBoxButton_Click(object sender, EventArgs e)
{
//Here should I add a code in order to delete dynamically created
//textboxes by clicking checkbox and button
}
}
Not sure of your question. But if I am right, this could do the trick.
SOLUTION1: While creating all the controls, add them to a List<Controls>. When you are checking the checkbox to delete the row, get the name of the checkbox, search it in the List<Controls>. So this way can get the index of the row of the checkbox clicked. Now delete the controls of that rows.
SOLUTION2: Create your controls in a TablelayoutPanel and everything will be easy.
EDIT
Copy paste everything in the form1, se btn_click as a event handler for a button. Let the size of the form a bit big. Everything should work fine now. If not working, let me know.
class MyControl
{
public TextBox txt1 { get; set; }
public TextBox txt2 { get; set; }
public TextBox txt3 { get; set; }
public TextBox txt4 { get; set; }
public CheckBox cb { get; set; }
public MyControl(TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4, CheckBox cb)
{
this.txt1 = txt1;
this.txt2 = txt2;
this.txt3 = txt3;
this.txt4 = txt4;
this.cb = cb;
}
}
List<MyControl> list = new List<MyControl>();
public int x = 50, n = 1;
TextBox txtTemp, txt1, txt2, txt3, txt4;
CheckBox cbTemp;
private void btn_Click(object sender, EventArgs e)
{
txtTemp = new TextBox();
txtTemp.Location = new System.Drawing.Point(10, x);
txtTemp.Name = "txt1_" + n;
txt1 = txtTemp;
txtTemp = new TextBox();
txtTemp.Location = new System.Drawing.Point(120, x);
txtTemp.Name = "txt2_" + n;
txt2 = txtTemp;
txtTemp = new TextBox();
txtTemp.Location = new System.Drawing.Point(230, x);
txtTemp.Name = "txt3_" + n;
txt3 = txtTemp;
txtTemp = new TextBox();
txtTemp.Location = new System.Drawing.Point(350, x);
txtTemp.Name = "txt4_" + n;
txt4 = txtTemp;
cbTemp = new CheckBox();
cbTemp.Name = "cb1_" + n;
cbTemp.Enter += new EventHandler(cbTemp_Enter);
cbTemp.Location = new System.Drawing.Point(490, x);
this.Controls.Add(txt1);
this.Controls.Add(txt2);
this.Controls.Add(txt3);
this.Controls.Add(txt4);
this.Controls.Add(cbTemp);
list.Add(new MyControl(txt1, txt2, txt3, txt4, cbTemp));
x += 40;
n++;
}
void cbTemp_Enter(object sender, EventArgs e)
{
if ((MessageBox.Show("Are you Sure?", "Warning", MessageBoxButtons.YesNo)) == DialogResult.No)
return;
CheckBox cbMain = (CheckBox)sender;
int index = Search(cbMain);
this.Controls.Remove(list[index].txt1);
this.Controls.Remove(list[index].txt2);
this.Controls.Remove(list[index].txt3);
this.Controls.Remove(list[index].txt4);
this.Controls.Remove(list[index].cb);
}
private int Search(CheckBox cbMain)
{
int temp = 0;
foreach (MyControl item in list)
{
if(cbMain.Name == item.cb.Name)
temp = list.IndexOf(item);
}
return temp;
}
For WinForms, I recommend putting the generated TextBoxes into the Tag field of the CheckBox. Then keep a managed list of all CheckBoxes. Once they click the delete button, iterate through the collection of CheckBoxes. If their state is checked, pull the TextBox out of the Tag field, remove it from the form collection, then delete it.
NOTE: This code is untested but should work in principle.
UPDATE: Reading your latest comment, instead of storing a single TextBox in the Tag, just create another List of them and store the entire list in the tag. Then iterate through those in the delete method.
private List<CheckBox> _checkboxes = new List<CheckBox>();
public void CreateTextBox( int i, StringReader r )
{
// ... do your stuff here
_cb[n].Tag = tb;
// ... finish up
_checkboxes.Add( _cb[n] );
}
public void DeleteTextBoxButton_Click( object sender, EventArgs e )
{
foreach( var cb in _checkboxes )
{
if( cb.Checked )
{
TextBox tb = cb.Tag as TextBox;
if( tb != null )
{
form2.Controls.Remove( tb );
}
}
}
}
Related
I wanna change the Text properties of Label using Buttons just like in hangman; but after I created the Label, I became confused when I try to access the specific Label
// creating label
for (int i = 0; i < numericUpDown1.Value; i++)
{
Label l = new Label();
l.Text = "_";
l.Width = 20;
l.Height = 25;
l.Left = i * 20 + 510;
l.Top = 20;
l.BackColor = Color.Transparent;
groupBox2.Controls.Add(l);
}
// function to change the label text
// if I clicked the button
// the first label text will be changed to the text in the button i clicked
private void B_Click(object sender, EventArgs e)
{
var thsBtn = (Button)sender;
bool benar = false;
if (benar == false)
{
thsBtn.Text = " ";
thsBtn.Enabled = false;
}
else
{
thsBtn.Enabled = false;
}
}
You can organize created Labels into a collection, say, List<Label>:
private List<Label> m_CreatedLabels = new List<Label>();
...
// Remove all previous labels
foreach (Label lbl in m_CreatedLabels)
lbl.Dispose();
m_CreatedLabels.Clear();
// Create new ones
for (int i = 0; i < numericUpDown1.Value; i++) {
m_CreatedLabels.Add(new Label() {
Text = "_",
Width = 20,
Height = 25,
Left = i * 20 + 510,
Top = 20,
BackColor = Color.Transparent,
Parent = groupBox2
});
}
Now you have m_CreatedLabels collection to work with created Labels, e.g.
private void B_Click(object sender, EventArgs e) {
var thsBtn = sender as Button;
// you may want to add a condition into FirstOrDefault(), e.g.
// .FirstOrDefault(lbl => lbl.Text == "_")
// - first label with "_" Text
Label lblToProcess = m_CreatedLabels
.FirstOrDefault();
if (null != lblToProcess)
lblToProcess.Text = thsBtn.Text;
thsBtn.Enabled = false;
}
One option here is to give your dynamically created Label instances a Name. From there, you should be able to use ControlCollection.Find to find your Label instances by name.
private void CreateLabels()
{
for (int i = 0; i < numericUpDown1.Value; i++)
{
Label l = new Label();
l.Name = $"DynamicLabel{i}";
l.Text = "_";
l.Width = 20;
l.Height = 25;
l.Left = i * 20 + 510;
l.Top = 20;
l.BackColor = Color.Transparent;
groupBox2.Controls.Add(l);
}
}
private void DoSomethingWithADynamicLabel(int dynamicLabelIndex)
{
Label l = groupBox2.Controls.Find($"DynamicLabel{i}", true).FirstOrDefault() as Label;
if (l is null)
{
// Couldn't find the label...
return;
}
// Do something with l
}
When creating the Label instances inside CreateLabels, I'm simply appending the for loop's counter to the string "DynamicLabel". This gives you a bunch of Labels with names like "DynamicLabel0", "DynamicLable1", "DynamicLabel2", etc...
Then in DoSomethingWithADynamicLabel, assuming you have the index of the Label you want to deal with, you can use groupBox2.Controls.Find to actually find the Label you're interested in. ControlCollection.Find returns Control[], so calling FirstOrDefault will take the first item from the array or null if no Control with the given name exists.
I've create an array of textboxes of rows and colums in EnterColsAndRows class. I need to use it in button_click method to create an array of int variables for each row and column.
public partial class EnterColsAndRows : Form
{
public int width_of_nonogram;
public int height_of_nonogram;
public EnterColsAndRows(int width, int height)
{
InitializeComponent();
width_of_nonogram = width;
height_of_nonogram = height;
TextBox[] textBox1 = new TextBox[width_of_nonogram];
TextBox[] textBox2 = new TextBox[height_of_nonogram];
for (int i = 0; i < width_of_nonogram; i++)
{
textBox1[i] = new TextBox();
textBox1[i].Text = "Col " + (i + 1);
Point p = new Point(20, 30 * i);
textBox1[i].Location = p;
this.Controls.Add(textBox1[i]);
}
for (int i = 0; i < height_of_nonogram; i++)
{
textBox2[i] = new TextBox();
textBox2[i].Text = "Row " + (i + 1);
Point p = new Point(200, 30 * i);
textBox2[i].Location = p;
this.Controls.Add(textBox2[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
}
You need to read about classes fields and properties
private TextBox[] textBox1;
private TextBox[] textBox2;;
...
public EnterColsAndRows(int width, int height)
{
...
textBox1 = new TextBox[width_of_nonogram];
textBox2 = new TextBox[height_of_nonogram];
...
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1 != null && textBox1.Length > 0)
{
textBox1[0].Text = "Awesome, i am"
}
}
Further reading
Classes (C# Programming Guide)
Fields (C# Programming Guide)
To access textbox array what you can do is :
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
var textbox = ((TextBox)x);//Your code goes here.
}
}
With this you will be able to access all the textboxes, what you can do is assign name to the textboxes in the EnterColsAndRows function and use it in the above code.
This has been a real struggle lately for me because this is what I need the most right now. I made 2 textboxes dynamic for a login form and want to get the values from the textboxes if I hit the login button. I have searched on the internet for possible values but none of them seem to work for me. The button and the textbox are made in a different class and that is the painful part for me. I cannot get the value from the textbox on the form to the event handler in the class where my buttons are made. If someone can help me with this one so I can go on with my project and be finish it off very soon.
I will leave some pieces of the code also for you. These pieces will be the class for the buttons and textboxes and the main form.
Main Form
x_loc = 0;
y_loc = 80;
x_size = 100;
y_size = 20;
foreach(string item in lon.loginLbls())
{
clsLbl = new Labels(pnlMenu, x_loc, y_loc, x_size, y_size, item);
y_loc += 50;
}
x_loc = 0;
y_loc = 100;
x_size = 200;
y_size = 30;
foreach(string item in lon.loginForm())
{
clsTxt = new Textboxes(pnlMenu, x_loc, y_loc, x_size, y_size, item);
y_loc += 50;
}
x_loc = 0;
y_loc = 200;
x_size = 200;
y_size = 30;
foreach(string item in lon.loginBtns())
{
clsBtn = new Buttons(pnlMenu, x_loc, y_loc, x_size, y_size, item);
y_loc += 50;
}
Button Class
Button btn;
public Buttons(Panel parent, int x_loc, int y_loc, int x_size, int y_size, string name)
{
btn = new Button();
btn.Location = new Point(x_loc, y_loc);
btn.Size = new Size(x_size, y_size);
btn.Text = name;
btn.Name = name;
btn.Click += new EventHandler(btnHandler);
btn.ForeColor = Color.Black;
btn.BackColor = Color.White;
parent.Controls.Add(btn);
}
private void btnHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
switch (btn.Text)
{
case "Login":
Login lgn = new Login();
break;
case "Afsluiten":
Application.Exit();
break;
}
}
Textbox Class
TextBox tb;
public Textboxes(Panel parent, int x_loc, int y_loc, int x_size, int y_size, string name)
{
tb = new TextBox();
tb.Location = new Point(x_loc, y_loc);
tb.Size = new Size(x_size, y_size);
tb.Name = name;
tb.ForeColor = Color.Black;
tb.BackColor = Color.White;
parent.Controls.Add(tb);
}
Lists
public List<string> loginBtns()
{
List<string> lgnBtns = new List<string>();
lgnBtns.Add("Login");
return lgnBtns;
}
public List<string> loginForm()
{
List<string> lgnForm = new List<string>();
lgnForm.Add("username");
lgnForm.Add("password");
return lgnForm;
}
public List<string> loginLbls()
{
List<string> lgnLbl = new List<string>();
lgnLbl.Add("Code");
lgnLbl.Add("Wachtwoord");
return lgnLbl;
}
Note: All these methods are located in a different class.
You have 2 ways to go:
1.Make creation on textboxes public:
partial class form1{
TextBox tb = new TextBox();
...
}
then can get get its text whereever you like:
string a = tb.Text;
2.Get Textbox Controls of Parent:
TextBox[] tb = parent.Controls.OfType<TextBox>().ToArray();
Now you have textboxes in an array. You may want to use the Tag to identify them:
string a = tb.FirstOrDefault(t=>(string)t.Tag=="username").Text;
Of course in this case you must have set the Tag when adding the TextBox.
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!
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;
}