Tuesday, November 17, 2009

Read Only For DropDownList

Some times we want to disable a control not to edit or change the value, but disabling a control becomes a bad look. An alternative is read only, it is possible to make a textbox as readonly by the property ReadOnly setting as true. but it is not possible for the DropDownList control.

We can't make a DropDownList control for read only in Asp.Net unlike doing  in windows applications.

One good solution is to disable all items except the selected one. The following DropDownList control (ddlAuctionStatus) has some items and an item is selected, then using the code will provide a readonly approach by disabling all unselected items

foreach (ListItem it in (ddlAuctionStatus.Items)
{
  if (it.Selected != true)
   it.Enabled = false;
}


The DropDownList box will show the selectedvalue only (may be selected by SelectedValue or SelectedIndex properties). It is realy like a read only box, we can't select other items.

To hide items dynamically by code as per the application's need, use the following example.

//To hide 1 & 3


(ddlAuctionStatus.Items[0] as ListItem).Enabled = false;
(ddlAuctionStatus.Items[2] as ListItem).Enabled = false;
 
The items 1 & 3 will disappear.

Thursday, October 29, 2009

GridView BoundColumn Date Format

aWhen using dates in GridView bound columns, It displays without any specified format. The date with time will display as a long length text. We can set the format what we need, use DataFormatString attribute with the BoundField column.

If we want to display the date as 25/12/2005 give DataFormatString="{0:dd/MM/yyyy}"
and also we have to set the HtmlEncode="False" to set the field value is not Html-encoded.

Example



... HtmlEncode="False" DataFormatString="{0:dd/MM/yyyy}"
DataField="recdate" HeaderText="CREATED DATE">"



For TemplateField, use the same format string within the Eval method of  Template (May be ItemTemplate, EditItemTemplate, etc...) as the second argument

 Example

       Eval("recdate","{0:dd/MM/yyyy}")