我有一个表单runat =“server”,id =“myform”。这是一个包含大量标签的个人资料页面。我从SQL数据库中获取输入文本。但是如果SQL数据库有空值,那么我希望他们的文本变为“未指定”。出于这个原因,我使用以下代码,但它无法正常工作。
foreach (Control item in myform.Controls)
{
Label lbl = null;
bool labelIsEmpty = false;
try
{
lbl = (Label)item;
labelIsEmpty = (lbl.Text == string.Empty && lbl != null);
}
catch
{
}
if (labelIsEmpty)
{
lbl.Text = "Not Specified";
}
}
答案 0 :(得分:3)
myform.Controls
将为您提供一个包含容器所有控件的集合(不仅仅是标签)。因此,您必须在迭代集合时检查控件的类型,以避免抛出异常。在附加注释中,您指定label has default text "Label"
,因此您还需要在条件中包含此注释。整个场景可以像下面这样实现:
foreach (Control item in myform.Controls)
{
if (item is Label)
{
var lbl = (Label)item;
bool labelIsEmpty = false;
try
{
lbl = (Label)item;
labelIsEmpty = (lbl != null && lbl.Text == string.Empty && lbll.Text!="Label");
}
catch
{
//Throw error message
}
if (labelIsEmpty)
{
lbl.Text = "Not Specified";
}
}
}
注意: -
您需要重新排序条件以避免异常。检查 在检查控制权为
string.Empty
后,null
应该出现。 因为如果是第一个,AND
将不会检查第二个条件 如果lbl.Text
为空,则NullReferenceException
会抛出lbl
答案 1 :(得分:0)
$featured_articles = get_field('featured_articles', false, false );
$id = $featured_articles[0];
//var_dump();
$numberOfArticles = count($featured_articles);
//var_dump($featured_articles);
echo "<div class='container'>";
echo "<div class='row-fluid'>";
for ($i=1; $i <= $numberOfArticles; $i++) {
if ($featured_articles) {
$id = $featured_articles[$i-1];
//var_dump($featured_articles);
if ( has_post_thumbnail($id) ) {
echo "<div class='span4'>";
echo "<article class='post__holder recipes'>";
echo "<a href='".get_permalink($id)."' class='image'>";
echo get_the_post_thumbnail( $id, 'medium-thumb' );
$image_large = wp_get_attachment_image_src( get_post_thumbnail_id($id), 'large');
echo "</a>";
}
echo "<a href='".get_permalink($id)."'><h3>".get_the_title($id)."</h3></a>";
echo "<div class='starRating'>";
echo "<img src='".home_url()."/wp-content/themes/BUZZBLOG-theme/images/StarRating.svg' alt='Testergebnis'>";
echo "<div class='bar' style='width:".get_field('rating', $id)."%'></div>";
echo "</div>";/** end starrating **/
echo "<a href='".get_permalink($id)."'><div class='readmore-button'>Zum Testbericht...</div></a>";
echo "</div>";
echo "</article>";
if($i%3==0) {
echo "<div class='clearfix'></div>";
}
}
}
echo "</div>";
echo "</div>";