Using
conditional (?:) Operator to save Check box state
Saving
the state of a CHECKBOX to the database in the INSERT mode and setting the
status in the View mode is a normal operations in any form based
application.
Conventionally
we use to write a code block to check the state of the CHECKBOX
(Checked/Unchecked) and save/set its state. The conventional code goes
like this.
Conventional Method
To insert data into the
Database
StringBuilder sbInsertQuery =
null;
sbInsertQuery = new
StringBuilder();
....
if (chkValid.Checked == true)
{
sbInsertQuery.Append("'Y',");
}
else
{
sbInsertQuery.Append("'N',");
}
...
DataAccessLayer.ExcuteQuery(sbInsertQuery.ToString());
To set the Checkbox state from
the Database data
if(dsDetails.Tables["dtDetails"].Rows[0]["VALID"].ToString()
== "Y")
{
chkValid.Checked = true;
}
else
{
chkValid.Checked = false;
}
As you could see we have
written 8 lines of code to check the state of the CHECKBOX and insert the state
into the Database, again we had to write 8 more lines of code to fetch the
details from the database and set it on the form field.
Now let us see on how this can
be optimized using the conditional (?:)
Operator, here is the code using the conditional (?:) Operator
Using the conditional (?:)
Operator
To insert data into the Database
StringBuilder sbInsertQuery =
null;
sbInsertQuery = new
StringBuilder();
....
sbInsertQuery.Append("'"
+ ((chkValid.Checked) ? "Y" : "N") + "',");
...
DataAccessLayer.ExcuteQuery(sbInsertQuery.ToString());
To set
the Checkbox state from the Database data
chkValid.Checked =
(dsDetails.Tables["dtDetails"].Rows[0]["VALID"].ToString()
== "Y")? true:false;
Just 2 lines of code, 1 to form
the Insert query and the other to set the state in the Form. Using the conditional (?:) Operator we have reduced the total
lines of code from 16 to just 2 lines.
That's
it, we have seen, the use of conditional (?:) Operator, in optimizing
the code in saving/setting the state of a CHECKBOX and to reducing the number
of lines of code.
No comments:
Post a Comment