Tuesday, November 23, 2010

Create/Remove Controls In/From a Containers like GroupBox Dynamically

My Task is " I developed an application by retrieving a list of Tables from the database into combobox. I choosed a table & Clicked 'OK' button, That Table should be display into the groupbox1 with labels & Textboxes. And when i choosed another Table from Combobox, old controls should be remove from the groupbox1 & again new controls should be generate according to numberofcolumns, fieldnames.

PROBLEM: The problem getting with "foreach" & "for ". Where the problem is resovled with "for "

If u wana see my code:
-----------------------------------------------------------------------------------------------

public void RemoveCtrls()
{
//MessageBox.Show(gb_DataBox.Controls.Count.ToString());

//foreach (Control ctrl in gb_DataBox.Controls)
//{
//if (!(ctrl is Button))//(ctrl.GetType() == typeof(Button)) //(((Button)ctrl).Text != "Next")
//{
// MessageBox.Show(ctrl.GetType().Name + " : " + ctrl.Name.ToString());
// gb_DataBox.Controls.Remove(ctrl);
// ctrl.Dispose();
//}
// }

int c = gb_DataBox.Controls.Count;

//for (int i = 1; i < i =" c">= 0; i--)
{
if (!(gb_DataBox.Controls[i] is Button))
{
//if (gb_DataBox.Controls[i].GetType().ToString())//.EndsWith(".ctl1"))

MessageBox.Show(gb_DataBox.Controls[i].GetType().Name + " : " + gb_DataBox.Controls[i].Name.ToString());
gb_DataBox.Controls.Remove(gb_DataBox.Controls[i]);
}
}
}

private void btn_ConnectDB_Click(object sender, EventArgs e)
{
//Make Default values
y = 20;
gb_DataBox.Height = 100;//50;

RemoveCtrls();
//cn = new SqlConnection("Data Source=.;Initial Catalog=master;User ID=sa;Password=123");

query = txtQuery.Text;
try
{
cmd = new SqlCommand(query, cn);

if (cn.State == ConnectionState.Open)
cn.Close();

cn.Open();
dr = cmd.ExecuteReader();

lb = new Label[dr.FieldCount];
txt = new TextBox[dr.FieldCount];

for (int i = 0; i < lb.Length; i++)
{
lb[i] = new Label();
txt[i] = new TextBox();
lb[i].Text = dr.GetName(i);
lb[i].Name = dr.GetName(i);
txt[i].Name = dr.GetName(i);
lb[i].Location = new Point(100, y + 3);
txt[i].Location = new Point(200, y);
//MessageBox.Show(lb[i].Text.ToString());
//MessageBox.Show(txt[i].Name.ToString());
gb_DataBox.Controls.Add(lb[i]);
gb_DataBox.Controls.Add(txt[i]);
y += 30;

gb_DataBox.Height += txt[i].Height;// +3;
this.Height = groupBox2.Height + gb_QueryBox.Height + gb_DataBox.Height + 100;
//this.AutoScroll = true;
int c = gb_DataBox.Controls.Count;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
cn.Close();
}
btn_Next.Enabled = true;
}

private void btn_Next_Click(object sender, EventArgs e)
{
if (dr.Read())
{
for (int i = 0; i < lb.Length; i++)
txt[i].Text = dr.GetValue(i).ToString(); //dr[i].ToString();
}
else
{
MessageBox.Show("No More Records..");
cn.Close();
btn_Next.Enabled = false;
}
}
------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Followers