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

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!

Related

C# remove last dynamically created textbox

Almost totally noob here. Im stucked. I know how to delete all dc textboxes but have no idea how to delete only last created one. Thx
piece of my code:
int B = 1;
public void NovIntRazd()
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = B * 30;
txt.Left = 26;
txt.Height = 20;
txt.Width = 65;
txt.Name = "txtIntRazd" + this.B.ToString();
B++;
}
If you only need to ever remove one textbox, you can just keep the reference to the last one:
int B = 1;
TextBox txt;
public void NovIntRazd()
{
txt = new TextBox();
this.Controls.Add(txt);
txt.Top = B * 30;
txt.Left = 26;
txt.Height = 20;
txt.Width = 65;
txt.Name = "txtIntRazd" + this.B.ToString();
B++;
}
public void RemoveLast()
{
if (txt == null) return;
Controls.Remove(txt);
txt = null;
}
Alternatively, a good practice is to put dynamically created controls in their own container, like a panel. It sounds like your case is a perfect use for a FlowLayoutPanel, which will handle control positioning too. When you remove any control, all the others are automatically moved around to the right places.
Then to remove the last added control, you can just do
if (pnl.Controls.Count > 0) pnl.Controls.RemoveAt(pnl.Controls.Count - 1);
If you really want to keep the controls mixed up in the top-level form, you can easily organize the dynamic textboxes by using a Stack:
Stack<TextBox> textboxes = new Stack<TextBox>();
public void NovIntRazd()
{
var txt = new TextBox()
{
Top = (textboxes.Count + 1) * 30,
Left = 26,
Height = 20,
Width = 65,
Name = "txtIntRazd" + (textboxes.Count + 1).ToString()
};
this.Controls.Add(txt);
textboxes.Push(txt);
}
public void RemoveLast()
{
if (textboxes.Count == 0) return;
Controls.Remove(textboxes.Pop());
}

Get real time input from programmatically generated elements in C# form

How to get value of checkboxes (and the textbox upon change in text) in real time with form particulars that are all generated via code?
This following code produces a form upon button press, the form has checkboxes and a richtextbox. Ideally I want any interaction to have an effect, so if I paste in a grid of ones and zeros the checkboxes update, and once a checkbox gets click, the corresponding one or zero in the textarea will update (So that I can then copy the grid (matrix) out and into another program.
I know how to get the events using the visual studio GUI maker, but not from a programmatically created form like this.
private void begin_button_Click(object sender, EventArgs e)
{
// Build the child form
Form check_box = new Form();
check_box.FormBorderStyle = FormBorderStyle.FixedSingle;
// Get the values from the textboxes
int height = Convert.ToInt16(this.height_input.Text);
int width = Convert.ToInt16(this.width_input.Text);
// Set the dimensions of the form
check_box.Width = width * 15 + 40;
check_box.Height = ( height * 15 + 40 ) * 3;
// Build checkboxes for the checkbox form
CheckBox[] chk;
chk = new CheckBox[height * width];
int count = 0;
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++)
{
chk[count] = new CheckBox();
chk[count].Name = count.ToString();
chk[count].Width = 15; // because the default is 100px for text
chk[count].Height = 15;
chk[count].Location = new Point(j * 15, i * 15);
chk[count].CheckedChanged += new EventHandler(this.CheckedChanged);
check_box.Controls.Add(chk[count]);
count += 1;
//Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count);
}
}
RichTextBox output_area;
output_area = new RichTextBox();
output_area.Location = new Point(chk[0].Location.X, chk[count-1].Location.Y + 30);
check_box.Controls.Add(output_area);
output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!";
output_area.Width = check_box.Width - 40;
output_area.Height = check_box.Height / 2;
// Run the form
check_box.ShowDialog();
}
EDIT:
I have added the event handler and it's working, however I can't access the checkbox form, only the main form.
private void CheckedChanged(object sender, EventArgs e)
{
//throw new NotImplementedException();
CheckBox x = (CheckBox)sender;
Console.WriteLine(x);
Console.WriteLine(x.Name.ToString());
}
Have a look at the .Designer file that the form designer generates for you!
Anyway, in your loop, try something like this:
chk[count].CheckedChanged += MyFancyHandler;
And the handler itself will look just like a normal handler:
private void MyFancyHandler( object sender, EventArgs e )
{
// ...
}
Also notice that the sender argument there will contain a reference to whichever checkbox/control the event refers to.
Below code updates matrix text in the rich text box when check box check state changed.
RichTextBox output_area;
CheckBox[] chk;
Size MatrixSize;
private void begin_button_Click()
{
// Build the child form
Form check_box = new Form();
check_box.FormBorderStyle = FormBorderStyle.FixedSingle;
check_box.StartPosition = FormStartPosition.CenterScreen;
// Get the values from the textboxes
int height = Convert.ToInt16("10");
int width = Convert.ToInt16("7");
MatrixSize = new Size(width, height);
// Set the dimensions of the form
check_box.Width = width * 15 + 40;
check_box.Height = (height * 15 + 40) * 3;
// Build checkboxes for the checkbox form
chk = new CheckBox[height * width];
int count = 0;
for (int i = 1; i <= height; i++)
{
for (int j = 1; j <= width; j++)
{
chk[count] = new CheckBox();
chk[count].Name = count.ToString();
chk[count].Width = 15; // because the default is 100px for text
chk[count].Height = 15;
chk[count].Location = new Point(j * 15, i * 15);
check_box.Controls.Add(chk[count]);
chk[count].CheckedChanged += new EventHandler(CheckBox1_CheckedChanged);
count += 1;
//Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count);
}
}
output_area = new RichTextBox();
output_area.Location = new Point(chk[0].Location.X, chk[count - 1].Location.Y + 30);
check_box.Controls.Add(output_area);
output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!";
output_area.Width = check_box.Width - 40;
output_area.Height = check_box.Height / 2;
// Run the form
check_box.ShowDialog();
}
private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
Debug.WriteLine(c.Name);
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 1; i <= MatrixSize.Height; i++)
{
for (int j = 1; j <= MatrixSize.Width; j++)
{
if (chk[count].Checked)
{
sb.Append("1,");
}
else
{
sb.Append("0,");
}
count += 1;
}
sb.Append("\r\n");
}
output_area.Text = sb.ToString();
}

Strange drawing behavior with labels

on startup I'm generating a lot of controls 90 to be exact and everything is working ok EXCEPT for the labels they are not being drawn or something? they are there because I can click them and they show proper ID (click event) here's the genereation code
private static bool ClientsLoaded = false;
private static WebBrowser[] Clients = new WebBrowser[45];
private static Label[] ClientLabel = new Label[45];
private static int MaximizedClient = -1;
public Form1()
{
InitializeComponent();
int WBoffsetX = 0;
int WBoffsetY = 0;
int lbloffsetX = 0;
int lbloffsetY = 0;
for (int i = 0; i < 45; i++)
{
var wb = new WebBrowser();
Clients[i] = wb;
wb.ScrollBarsEnabled = false;
wb.Height = 12;
wb.Width = 12;
wb.Location = new Point(2 + WBoffsetX, 2 + WBoffsetY);
WBoffsetX += 13;
wb.ScriptErrorsSuppressed = true;
this.Controls.Add(wb);
ClientLabel[i] = new Label();
ClientLabel[i].Name = "lbl_" + i;
ClientLabel[i].Font = new Font("Arial", 12);
ClientLabel[i].ForeColor = System.Drawing.Color.White;
ClientLabel[i].Location = new Point(12 + lbloffsetX, 450 + lbloffsetY);
lbloffsetX += 22;
ClientLabel[i].Click += new EventHandler(lbl_click);
ClientLabel[i].Text = "C" + i + ": o";
this.Controls.Add(ClientLabel[i]);
}
}
I've tried adding a button with for(45) clientlabel[i].Refresh() and it did nothing I tried changing the visibilty of them all to false and then back to true and nothing however I did find 1 thing interesting if I hide lbl_1 label 2 text will appear if I had label 2 label 3 text will appear but if I change the previous label back to visible they stay invisible textwise
I can click in a line on the form and
private void lbl_click(object sender, EventArgs e)
{
int id = -1;
var s = sender.ToString();
for(int i = 0; i<=45; i++)
{
if (s.Contains("C" + i + ":"))
{
id = i;
}
}
MessageBox.Show("Hello label, " + id);
}
will pop up the proper ids etc
does anyone know what's causing this maybe? or how to fix it
Well, I don't know what is the problem. This code works well enough and it has only marginal differences with the original(AutoSize property, explicit statement of Height and Width, and minor Location adjustment):
for (int i = 0; i < ClientLabel.Length; i++)
{
// Web browsers
WebBrowser wb = new WebBrowser()
{
ScrollBarsEnabled = false,
Height = 12,
Width = 12,
Location = new Point(2 + WBoffsetX, 2 + WBoffsetY),
ScriptErrorsSuppressed = true
};
WBoffsetX += 13;
Clients[i] = wb;
// Labels
Label label = new Label()
{
Name = "label_" + i,
Text = "Data",
AutoSize = true,
Location = new Point(50 + lbloffsetX, 50 + lbloffsetY),
Width = 100,
Height = 20,
Font = new Font("Arial", 12),
ForeColor = System.Drawing.Color.White,
};
label.Click += new EventHandler(lbl_click);
ClientLabel[i] = label;
lbloffsetX += 30;
}
this.Controls.AddRange(Clients);
this.Controls.AddRange(ClientLabel);

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

C# deleting dynamic textboxes by checkboxing

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 );
}
}
}
}

Categories