I need to populate some user controls in a group box (from a database) based on what the user selects in one of the controls.
Each control is to be populated by a column from a table in a database. The values are occasionally null, sometimes strings, and sometimes integers. The query will return only one row of data.
The group box contains many different types of controls; however, I only need to populate the read only text boxes.
Below is how I went about solving this. My code works, but seems clunky to me. IE. nested try/catch and nested loops/conditional statements.
Is there a simpler/better/cleaner way to accomplish this?
ERPDB.sqlGetDataReader
returns takes a sql statement string as an argument and returns a OracleDataReader
.
sqlString
takes a the user input from a user control and returns aa sql query as a string with multiple columns.
private void populateReadOnlyColumns()
{
OracleDataReader dr = ERPDB.sqlGetDataReader(sqlString(userSelection));
while (dr.Read())
{
int i = 0;
foreach (Control control in groupBox1.Controls)
{
if( control is TextBox)
{
TextBox txtBox = (TextBox)control;
if (txtBox.ReadOnly == true)
{
safeString(dr, txtBox, i);
i++;
}
}
}
}
}
private void safeString(OracleDataReader dr, Control control, int index)
{
try
{
try
{
control.Text = dr.GetString(index);
}
catch
{
control.Text = Convert.ToString(dr.GetInt32(index));
}
}
catch
{
control.Text = "";
}
}
private string sqlString(string userSelection)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("SELECT description");
sb.AppendLine(" ,job_title");
sb.AppendLine(" ,category");
sb.AppendLine(" ,risk_code");
sb.AppendLine(" ,exempt_flag");
sb.AppendLine(" ,pay_grade");
sb.AppendLine(" FROM emp_jobs");
sb.AppendLine(" WHERE job_code = '" + userSelection.Trim() + "'");
return sb.ToString();
}
Well one way you can make it simpler/cleaner is by using LINQ:
int i = 0;
foreach (TextBox txtBox in (from Control control in groupBox1.Controls
where control is TextBox && ((TextBox)control).ReadOnly
select control))
safeString(dr, txtBox, i++);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.