Child controls (textbox, combo etc.) in a .NET container controls (like a
Form), can be accessed and their properties set at runtime dynamically by accessing the control array.
Using the Code
The following example deals with runtime validation (which checks for compulsory data input) of Windows Forms controls like
ComboBox but can be expanded to handle validation and appearance of all types of Windows Forms controls.
To implement this example, you must create a database table which would hold the configuration for all the controls in the forms. You can also use an XML file instead of a database table.
I have attached the SQL to create the MS SQL 2000 database as well as the database backup. You have to create and configure the database at your end. After you restore the database, you will see that the table 'Ctlvalidation' has the form name, the control name, message and compulsory flag fields.
Our application will read this table and depending upon the flag set in the
Compulsory field, will make the control compulsory or non compulsory.
In our application, we create the
CompulsoryLogic class, which we can then call from any form in the application. In this class, we first create a database connection and fill the
string source = "server=CHAYAN;uid=mine;pwd=mine;database=CtlValidation";
string select =
"Select CtlName,Msg from CtlValidation where Compulsory>0 and Form ='"+
SqlConnection conn = new SqlConnection(source);
SqlDataAdapter da = new SqlDataAdapter(select,conn);
DataSet ds = new DataSet();
Then we loop through each
DataRow in the
DataSet and for each control in the form, check the validation for the required control (textbox, rich textbox or combo).
foreach(DataRow dr in ds.Tables.Rows)
foreach (Control c in frm.Controls)
if (c.Name == dr.ToString())
if (c.Text =="")
MessageBox.Show(dr.ToString()+" is a compulsory field",
c.BackColor = Color.AliceBlue;
Once this is done, we can call the
CompulsoryLogic class from any form where a control validation is required.
private void button1_Click(object sender, EventArgs e)
A very similar concept can be used in providing menu based security to user groups in a desktop application but we will discuss that in a separate article.
- MS SQL 2000
- VS.NET 2003 (C#)
Chayan Ray has been working as a Technical Consultant in a CMM level 5 company in India. His technical domain includes ASP.NET, C#, PHP, Perl, Cold Fusion, MySQL and MSSQL 2000.