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();
}
Related
I have created WinForm App in which user can set how many textboxes he want (Range 1-99)
I am using this code to create Textboxes during runtime
for (int i = 0; i < Calculation.Num; i++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
}
Suppose user create 2 textboxes and then enter data in each textbox and click calculate button
Now i want to get the textboxes data and divide it by 100
See The Picture I want txtbox1 and txtbox2 data
EDIT 3:
This is the Whole Code
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 GPA_Calculatior__New_
{
public partial class Form1 : Form
{
int j = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Label + Marks Obtained Textbox
for (int i = 0; i < Calculation.Num; i++)
{
Label lblCount = new Label();
lblCount.Name = "lblCount" + i;
lblCount.Location = new System.Drawing.Point(5, 55 + (20 * i) * 2);
lblCount.Size = new System.Drawing.Size(20, 30);
lblCount.Text = (i + 1).ToString();
this.Controls.Add(lblCount);
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
}
//Creating Textbox which is for total marks
for (j = 0; j < Calculation.Num; j++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "TotaltxtBox" + j;
txtRun.Location = new System.Drawing.Point(160, 50 + (20 * j) * 2);
txtRun.Size = new System.Drawing.Size(50, 25);
txtRun.Text = "100";
txtRun.Enabled = false;
this.Controls.Add(txtRun);
}
// Creating 2 Buttons (Calculate and Back)
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
Btn.Click += button_Click;
this.Controls.Add(Btn);
}
//Just for Giving free space in last
Label lbl = new Label();
lbl.Name = "lbl" + j;
lbl.Location = new System.Drawing.Point(30, 90 + (20 * j) * 2);
lbl.Size = new System.Drawing.Size(90, 30);
lbl.Text = "";
this.Controls.Add(lbl);
//**********************************************
}
//Caculate and back button function
private void button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Name.Equals("btn1"))
{
for (int i = 0; i < Calculation.Num; i++)
{
}
}
else
{
GPA_Calculator mainForm = new GPA_Calculator();
mainForm.Show();
this.Hide();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
for (j = 0; j < 10; j++)
{
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
var sum = this.Controls.OfType<TextBox>()
.Where(t => char.IsDigit(t.Name.Reverse().Take(1).FirstOrDefault())
&& t.Enabled)
.Select(t =>
{
double i;
if (!double.TryParse(t.Text, out i)) { return 0d; }
return i / 100d;
})
.Sum();
This may work, I built a separate class to store the control and its value, then you can work out the values independently from the rest of the form. You need to trigger the calculations though:
private List<InfoTextBox> activeTextBoxes = new List<InfoTextBox>();
public Form1()
{
for (int i = 0; i < Calculation.Num; i++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
InfoTextBox iBox = new InfoTextBox();
iBox.textbox = txtRun;
activeTextBoxes.Add(iBox);
}
}
public class InfoTextBox
{
private double _textboxValue;
public TextBox textbox { get; set; }
public double TextBoxValue { get { return _textboxValue; } set { _textboxValue = setValue(value); } }
private double setValue(double invalue)
{
return invalue / 100;
}
}
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!
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);
I am trying to add controls to a panel from a foreach loop.
When i press the button i want every element from a array to show as checkbox. This is wordking fine, then i want a numeric updown behind the checkbox so users can select a value.
The code for creating the checkboxes works just fine, for every item in my array it displays e checkbox. But it only shows 1 NumericUpDown.
Can anybody tell me why it only shows 1 numeric updown, while it shows all of the checkboxes?
Here is my code:
private void bierButton_Click(object sender, EventArgs e)
{
int height = 1;
int padding = 10;
int i = 0;
int x = 0;
CheckBox[] chk = new CheckBox[10];
NumericUpDown[] nmr = new NumericUpDown[10];
orderBox.Clear();
hideBtn();
foreach (string bieren in Drinks.bier)
{
chk[i] = new CheckBox();
nmr[i] = new NumericUpDown();
chk[i].Name = i.ToString();
chk[i].Text = Drinks.bier[i];
chk[i].TabIndex = i;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 0 + padding + height, 200, 22);
panel1.Controls.Add(chk[i]);
testPanel.Controls.Add(nmr[i]);
height += 22;
i++;
}
}
It appears you are not updating the position of your NumericUpDown controls.
All of them are there, they are just on top of one another.
Consider this change:
private void bierButton_Click(object sender, EventArgs e)
{
int height = 1;
int padding = 10;
int i = 0;
int x = 0;
CheckBox[] chk = new CheckBox[10];
NumericUpDown[] nmr = new NumericUpDown[10];
orderBox.Clear();
hideBtn();
foreach (string bieren in Drinks.bier)
{
chk[i] = new CheckBox();
nmr[i] = new NumericUpDown();
chk[i].Name = i.ToString();
chk[i].Text = bieren; // Drinks.bier[i];
chk[i].TabIndex = i;
chk[i].AutoCheck = true;
chk[i].Bounds = new Rectangle(10, 0 + padding + height, 200, 22);
// Start New Code
nmr[i].Bounds = new Rectangle(10, 0 + padding + height, 200, 22);
// End New Code
panel1.Controls.Add(chk[i]);
testPanel.Controls.Add(nmr[i]);
height += 22;
i++;
}
}
I also changed one line to chk[i].Text = bieren;.
I want to create 10 buttons on my form when I click on button1. No error with this code below but it doesnt work either.
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < buttons.Capacity; i++)
{
this.Controls.Add(buttons[i]);
}
}
You aren't creating any buttons, you just have an empty list.
You can forget the list and just create the buttons in the loop.
private void button1_Click(object sender, EventArgs e)
{
int top = 50;
int left = 100;
for (int i = 0; i < 10; i++)
{
Button button = new Button();
button.Left = left;
button.Top = top;
this.Controls.Add(button);
top += button.Height + 2;
}
}
It doesn't work because the list is empty. Try this:
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < 10; i++)
{
Button newButton = new Button();
buttons.Add(newButton);
this.Controls.Add(newButton);
}
}
You could do something like this:
Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);
}
If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.
Two problems- List is empty. You need to add some buttons to the list first. Second problem: You can't add buttons to "this". "This" is not referencing what you think, I think. Change this to reference a Panel for instance.
//Assume you have on your .aspx page:
<asp:Panel ID="Panel_Controls" runat="server"></asp:Panel>
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < buttons.Capacity; i++)
{
Panel_Controls.Controls.Add(buttons[i]);
}
}
use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3
private void button1_Click(object sender, EventArgs e)
{
int h =3;
Button[] buttonArray = new Button[8];
for (int i = 0; i <= h-1; i++)
{
buttonArray[i] = new Button();
buttonArray[i].Size = new Size(20, 43);
buttonArray[i].Name= ""+i+"";
buttonArray[i].Click += button_Click;//function
buttonArray[i].Location = new Point(40, 20 + (i * 20));
panel1.Controls.Add(buttonArray[i]);
} }
I had the same doubt and came up with the following contribution:
int height = this.Size.Height;
int width = this.Size.Width;
int widthOffset = 10;
int heightOffset = 10;
int btnWidth = 100; // Button Widht
int btnHeight = 40; // Button Height
for (int i = 0; i < 50; ++i)
{
if ((widthOffset + btnWidth) >= width)
{
widthOffset = 10;
heightOffset = heightOffset + btnHeight
var button = new Button();
button.Size = new Size(btnWidth, btnHeight);
button.Name = "" + i + "";
button.Text = "" + i + "";
//button.Click += button_Click; // Button Click Event
button.Location = new Point(widthOffset, heightOffset);
Controls.Add(button);
widthOffset = widthOffset + (btnWidth);
}
else
{
var button = new Button();
button.Size = new Size(btnWidth, btnHeight);
button.Name = "" + i + "";
button.Text = "" + i + "";
//button.Click += button_Click; // Button Click Event
button.Location = new Point(widthOffset, heightOffset);
Controls.Add(button);
widthOffset = widthOffset + (btnWidth);
}
}
Expected Behaviour:
This will generate the buttons dinamically and using the current window size, "break a line" when the button exceeds the right margin of your window.
First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:
for (int i = 0; i < 10; ++i)
{
var button = new Button();
button.Location = new Point(button.Width * i + 4, 0);
Controls.Add(button);
}
You can't add a Button to an empty list without creating a new instance of that Button.
You are missing the
Button newButton = new Button();
in your code plus get rid of the .Capacity