Forum guidelines
  • Home
  • »
  • C# Language
  • »
  • How to know dynamically created chekboxes is selected or not
AuthorQuestion
How to know dynamically created chekboxes is selected or not
Posted By Vishal Deb on 08 May 2013
Hi All

I am trying to generated the dynamic labels depending on the checked checkboxes which are dynamically created.

My .Net frame is 3.5
Here is code for dynamic checkboxes

System.Windows.Forms.CheckBox[] checkBox = new System.Windows.Forms.CheckBox[bran_count];

            for (int i = 0; i < bran_count; ++i)
            {
                checkBox[i] = new CheckBox();
                checkBox[i].Name = "radio" + Convert.ToString(i);
                checkBox[i].Text = ds2.Tables[0].Rows[i][2].ToString();
                
                checkBox[i].Location = new System.Drawing.Point(125 * i, 15);
                groupBox1.Controls.Add(checkBox[i]);
                checkBox[i].CheckStateChanged += new System.EventHandler(CheckBoxCheckedChanged);
                
            }
        }
        private void CheckBoxCheckedChanged(object sender, EventArgs e)
        {
            //MessageBox.Show();
        }
Any guidance is welcome, if possible give some code snippet.
Regards

AuthorReply
Re: How to know dynamically created chekboxes is selected or not
Posted By Shankar M on 11 May 2013  

Hi Vishal,

You can register a event for CheckStateChanged and get the Labels of the TextBoxes created. Here I have displayed the Name and State of the Check Box by handling CheckBoxChecked Event.

Program

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 Dynamically_created_chekboxes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            CheckBox[] chk = new CheckBox[5];


            for (int i = 0; i < 5; i++)
            {
                chk[i] = new CheckBox();
                chk[i].Name = "CheckBox" + i;
                chk[i].Text = "CheckBox " + i;


                chk[i].Location = new Point(100,50 *i);
                chk[i].CheckedChanged += new EventHandler(CheckBoxChecked);
                this.Controls.Add(chk[i]); 
            }
        }


        private void CheckBoxChecked(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            MessageBox.Show(string.Format("{0} is {1}",chk.Name,chk.CheckState),"Check Box State"); 
        }  
    }
}



Thanks, Shankar M

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.