Dynamic Dropdown in C# .Net

namespace Dynamic
{
//Code By Britman Dated 17-02-2011 To Creat Dynamic Dropdownlist
public partial class Form1 : Form
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
int i = 0;
int x = 0, y = 0;

public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(942, 468);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}

private void Form1_Load(object sender, EventArgs e)
{

x = 0;
y = 0;

i = i + 1;
string[] strTypes = new string[] {"A", "O", "E"};

ComboBox ddlDynamicDropDown = new ComboBox();
ddlDynamicDropDown.Location = new Point(x, y);
ddlDynamicDropDown.Width = 150;
ddlDynamicDropDown.Text = "--Select--";
ddlDynamicDropDown.Items.AddRange(strTypes);
ddlDynamicDropDown.Name = i.ToString();
ddlDynamicDropDown.SelectedIndexChanged += new System.EventHandler(doEvents);
this.Controls.Add(ddlDynamicDropDown);
}

private void button1_Click(object sender, EventArgs e)
{


}



public void doEvents(object sender, EventArgs e)
{



ComboBox ddlDynamicDropDownSender = sender as System.Windows.Forms.ComboBox;

if (ddlDynamicDropDownSender.Text == "A" || ddlDynamicDropDownSender.Text == "O")
{
if (Convert.ToInt32(ddlDynamicDropDownSender.Name) >= i)
{
//x = x + 20;
y = y + 20;
i = i + 1;
string[] strTypes = new string[] { "A", "O", "E" };

ComboBox ddlDynamicDropDown = new ComboBox();
ddlDynamicDropDown.Location = new Point(x, y);
ddlDynamicDropDown.Width = 150;
ddlDynamicDropDown.Text = "--Select--";
ddlDynamicDropDown.Items.AddRange(strTypes);
ddlDynamicDropDown.Name = i.ToString();
ddlDynamicDropDown.SelectedIndexChanged += new System.EventHandler(doEvents);
this.Controls.Add(ddlDynamicDropDown);
}


}
else
{

int x = i;
for (x = Convert.ToInt32(ddlDynamicDropDownSender.Name)+1; x <= i; x++)
{


ComboBox ddlDynamicDropDown = FindControl(x.ToString()) as System.Windows.Forms.ComboBox;

this.Controls.Remove(ddlDynamicDropDown);
y = y - 20;
}

i = Convert.ToInt32(ddlDynamicDropDownSender.Name);



}

}

private Control FindControl(string ControlName)
{
if (ControlName.Length == 0 || this.Controls.Find(ControlName, true).Length == 0)
return null;


return this.Controls.Find(ControlName, true)[0];

}
}
}

No comments:

Post a Comment