Thursday, March 23, 2006

C# retrieving values from dynamic created fields runtime

Finding proper source code to create form fields on a Windows application in C# at runtime was not so difficult to find.
Getting an example on how to access the fields created at runtime based on names created in a loop is another matter.
After finding source code in some forum for accessing some fields inside of a datagrid, I came up with the following to specifically access checkboxes:

// --- Code Start ---

int iCounter = 0;
int iNumberOfObjects = 0;
string strName = "";
string strState = "";
string strType = "";
iNumberOfObjects = this.Controls.Count;
if (iNumberOfObjects > 0) {
foreach(System.Windows.Forms.Control dgi in this.Controls) {
strType = dgi.GetType().ToString();
strName = dgi.Name;
if (strType == "System.Windows.Forms.CheckBox") {
strState = dgi.ToString();
iCounter++;
}
}
}

// --- Code End ---

Note: The line checking the number of objects and the foreach line reference fields which are directly on the main form. When accessing fields in a panel or elsewhere, then those two lines have to be adjusted. This is working C# code which was created just to see if something actually works.

No comments:

Post a Comment