Thursday, October 14, 2010

Adding a border around text to make it look like a TextBox

The scenario applies to simple Label or Literals in ASP.NET. I am currently using a DynamicControl with the Mode set to ReadOnly. This causes the generation of a Literal and thus looks like plain text in the browser. This is great in most cases.

However, sometimes I want the text to have a border around it and maybe a different background to make it look like a read only TextBox.

Thankfully there is an easy solution. Using CSS we can define a style

.DDTextWithBorder
{
        border: solid 1px #bcbcbc;   
}

We could include background color if we wanted to change that also.

To use the style, we can put a span tag around whatever we want the border around and setting the class=”DDTextWithBorder” attribute.

An example of that is:

<span class="DDTextWithBorder"><asp:DynamicControl ID="TotalPointsDynamicControl" runat="server" DataField="TotalPoints" Mode="ReadOnly"/></span>

Another way is to just set the CssClass property of the control we want to put a border around.

<asp:DynamicControl ID="TotalPointsDynamicControl" runat="server" DataField="TotalPoints" Mode="ReadOnly" CssClass="DDTextWithBorder"/>

That’s it. Quite simple, but powerful.

4 comments:

digital id said...

What is the reason to add a border around text to make it look like a TextBox.Why not make a text box non editable?Although you are right that the css you wrote will give readonly textbox effect to labels.But why is it actually needed can you give some example where it applies

Brent V said...

Hi digital id,

The difference is that a literal does not submit as a form value. I was looking for a way to not change how the Dynamic Data Text control was implemented and only change the way it looked. The idea was to minimize changes that could break things. In my case, I really just wanted certain fields to look a certain way and this allowed me to do it easily. In most cases, either one will work. Depending on what context you are working in you may want the form values to be submitted, in others you may not. This is just an alternative.

Anonymous said...

Relialize this is an old post but just for the record, this works too:



.TextBoxStyle
{
text-align:left;
border-color: #7F9DB9;
border-width: 1px;
border-style: solid;
font-family: Calibri;
font-size: 14px;
}

Then you can set your text property from code behind

Anonymous said...

Above post deleted my markup. Net-net just create a label and give it the TextBoxStyle. Set width (and even multiline) parameters just as you would with a real textbox