Dynamic Controls in .Net C#
A Simple example how to create Dynamic Control while looping through a dataset
using System;
using System.Data;
……….
String _con = "uid=dmadmin;pwd=pass123;Initial Catalog=candidate;server=SERVER56;";
DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(_con);
SqlCommand selectCmd = conn.CreateCommand();
selectCmd.CommandText = "SELECT * FROM Questions ";
SqlDataAdapter adp = new SqlDataAdapter(selectCmd);
adp.Fill(ds);
int ly = 148, cy = 165, backly = 251, totally=180;
for (i = 0; i <>
{
CheckBox chk = new CheckBox();
chk.Name = "chk" + ds.Tables[0].Rows[i]["ToDoID"].ToString();
chk.Click += new System.EventHandler(this.chk_CheckStateChanged);
chk.Location = new Point(cx, cy + i * 19);
chk.Size = new Size(236, 15);
chk.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular);
this.Controls.Add(chk);
if (ds.Tables[0].Rows[i]["Completed"] != DBNull.Value && ds.Tables[0].Rows[i]["Completed"] != null)
{
chk.Checked = true;
chk.Enabled = false;
}
if (ds.Tables[0].Rows[i]["Title"] != DBNull.Value && ds.Tables[0].Rows[i]["Title"] != null)
chk.Text = ds.Tables[0].Rows[i]["Title"].ToString();
}
}
private void chk_CheckStateChanged(object sender, EventArgs e)
{
MessageBox.Show( ((CheckBox)sender).Name.Replace("chk",""));
}

0 Comments:
Post a Comment
<< Home