Friday, June 03, 2005

How to hide null ASP.NET data fields



Say you have a bit of data called Symptoms that you want to display on your web page, and it contains a label (also called "Symptoms"). It might look something like this in your form:


Symptoms: <%# DataBinder.Eval(Container.DataItem, "Symptoms") %>


Now say, if there is no data in the database, you don't want the field to appear at all. I did some research to find a nice way to do this, but I didn't like any of them (if someone has a nice server side way of doing this (without peppering the html with >1 "DataBinder.Eval...", I'd like to hear).

So, here's my solution. First, decorate your html with a div and a span like this:


<div class="hide" id="SymptomsDiv">
Symptoms:
<span id="SymptomsSpan"><%# DataBinder.Eval(Container.DataItem, "Symptoms") %></span>
</div>


Then add the following css classes:
<style type="text/css">
.hide{display: none;}
.show{display: block;}
</style>


And the following script code:

<script>
function sectionObjects(name){
o = new Object;
o.name = name;
o.div = document.getElementById(name+"Div");
o.span = document.getElementById(name+"Span");
return o;
}
window.onload = function(){
var sections = new Array;
sections.push(sectionObjects("Symptoms"));

// Show those sections that have data
for(var i = 0; i<sections.length; i++)
if (sections[i].span.innerHTML!="")
sections[i].div.className = "show";
}
</script>


All the sections (all one in this case) start out hidden. The onload function runs when the window loads. It finds any sections that are not null using .innerHTML -- this'll work on all modern browsers.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?