Monday 8 June 2015

How to generate TextBox and Label on runtime in Windows Application using C# .Net


Note: In this concept we will discuss how to generate Textbox and Label in runtime and
How to get generate Textbox value in Message Box

First Step: we will take a Windows Application and select Windows Form which name is From2

Code for Form2.......................................

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 this namespace....
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{

}

int txtleft,lblleft,no;
int txtcount,lblcount = 1;

private void btnGenetrateText_Click(object sender, EventArgs e)
{
ClearText();
txtleft = 5;
lblleft = 5;
no = Convert.ToInt32(txtno.Text);
for (int i = 1; i <= no; i++)
{
AddNewTextBox();
AddNewLabel();
}

}
//Generate Label on Run time

public Label AddNewLabel()
{
Label l1 = new Label();
this.Controls.Add(l1);
l1.Top = lblleft * 25;
l1.Left = 25;
lblleft = lblleft + 1;
l1.Name = "Label" + lblcount;
l1.Text = "Subject" + lblcount;
lblcount++;
return l1;
}

//code for Generate TextBox on Run time

public TextBox AddNewTextBox()
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = txtleft * 25;
txt.Left = 100;
txtleft = txtleft + 1;
txt.Name = "txtTextBox" + txtcount;
return txt;

}
//code for remove Generated Label and TextBox
public void ClearText()
{
txtcount = 1;
lblcount = 1;
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
if (c.Name != "txtno")
c.Visible = false;
}
if (c.GetType()==typeof(Label))
{
if (c.Name != "lblno")
c.Visible = false;
}
}
}
//code for remove Generated Label and TextBox
string result;
private void btnGetTextBoxValue_Click(object sender, EventArgs e)
{
result = "";
foreach (Control c in this.Controls)
{
if (c.GetType()==typeof(TextBox))
{
if (c.Name != "txtno")
{
result += c.Text + ",";
}
}
}
MessageBox.Show(result.Remove(result.Length - 1));
}

//code for clear Generated TextBox value
private void btnClearTextBox_Click(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(TextBox))
{
if (c.Name != "txtno")
c.Text = "";

}
}
}
}
}




0 comments:

Post a Comment