DataFormatString won’t be applied

2 Jul 2007 In: English posts

If you are looking for an answer why DataFormatString won’t be applied at your BoundField, the most reasonable answer is “It’s a bug”. A bug for which nobody at Microsoft seems to be responsible for.

In few words, if you have a BoundField object bound to a field of type DateTime (or whatever you want) with a DataFormatString like this:

<asp:BoundField DataField=”DateOfBirth” DataFormatString=”{0:MM/dd/yyyy}” />

when you will run your web application, the output instead to be as everybody would expect (MM/dd/yyyy) appears to be formatted using its ToString() method like so:

07/02/2007 7:35:54 PM

The problem is reconducible to an effort of preventing cross site scripting attacks, so the field value is HtmlEncoded before the new formmating is applied. This internally changes the output that doesn’t match anymore to a suitable Date format and for this reason the format requested won’t apply.

The resolution is to set up the HtmlEncode to false like so:

<asp:BoundField DataField=”DateOfBirth” DataFormatString=”{0:MM/dd/yyyy}” HtmlEncode=”false”/>

Technorati Tags: DataFormatString, HtmlEncode

It was long time that don’t get into an ASP.Net project, and since I was standing at ASP.Net 1.1, this was the best occasion to wipe out the old conoissance and start with the new control released with ASP.Net 2.0

Between the new controls shipped with the "new" framework there is the FormView, an interesting control. As usual in Microsoft did a great job, but as usual too they forget to leave clean and easy the obviously things.

For people used to the old approach, accessing at page’s controls means to declare a protected internal HtmlGenericControl inside the code behind file (if the control was a stanrdard HTML control surrounded with the attribute runat="server") or a variable of the same type of the object dragged into the page.

Within the FormView this kind of approach doesn’t work at all. The FormView act as a sort of closed box inaccessible from the code-behind file. At least, on a first look it was what I though.

Also using the FindControl method doesn’t let me the expected results.

So, after some researches, I finally understood that inside the page’s OnLoad method, the FormView has not been initialized; the control contained inside the FormView doesn’t exist in the page scope yet. To get access them is necesary wait that all controls will created and then simple access to them using the ItemCreated event of the object.

Example:

protected void FormView1_ItemCreated(object sender, EventArgs e)
{
  Panel myPanel = (Panel)FormView1.FindControl("myPanel");
  if (true)
    myPanel.Visible = false;
  else
    ......
}

Another thing that let me lost some time was to try get access at the DataSource binded to the FormView. Also here, after some research, the code necessary to do this is:

Example:

protected void FormView1_DataBound(object sender, EventArgs e)
{   
   DataRowView r = (DataRowView)FormView1.DataItem;
   ....
}

In this way the DataRowView object will capture the content of the binded DataSource and, through the Row property accessible within its index, it will be possible to retrieve the single item of the returned data.

Era da tempo che non riprendevo un progetto ASP.Net in mano e visto che mi ero fermato ad ASP.Net 1.1, quale buona occasione per dare una rispolverata e vedere alcuni dei nuovi controlli del 2.0.

Tra questi il FormView, interessante. Come al solito in casa Microsoft hanno fatto tanto lavoro, ma puntualmente le cose più ovvie non le mettono mai a portata di mano.

Abituato al vecchio approccio, quando avevo bisogno di accedere ad un controllo nella pagina dal code behind, dichiaravo molto semplicemente una variabile protected internal di tipo HtmlGenericControl se si trattava di un controllo HTML standard “taggato” con l’attributo runat=”server” o di tipo indentico a quello impostato nell’IDE e semnplicemente accedevo al controllo utilizzando la variabile locale.

Con il FormView questo sistema non funziona. Il FormView crea una sorta di scatola chiusa inaccessibile dall’esterno. Almeno a prima vista sembra così.

Anche usando il metodo FindControl non ero in grado di accedere ai controlli dichiarati all’interno del FormView.

Dopo alcune ricerche ho finalmente capito che nel metodo OnLoad della pagina, il FormView non è stato ancora del tutto inizializzato; i controlli al suo interno ancora non esistono nello scope della pagina. Per potervi accedere è quindi necessario attendere che i controlli esistano ed in particolare utilizzare l’evento ItemCreated.

Esempio:

protected void FormView1_ItemCreated(object sender, EventArgs e)

{

    Panel myPanel = (Panel)FormView1.FindControl(“myPanel”);

    if (true)

        myPanel .Visible = false;

     else

        ……

}

Altra cosa che mi ha fatto perdere un pò di tempo è stata quella di cercare di accedere ai dati associati al dataSource associato al FormView. Anche qui dopo alcune ricerche la soluzione è traducibile così:

Esempio:

protected void FormView1_DataBound(object sender, EventArgs e)

{

    DataRowView r = (DataRowView)FormView1.DataItem;

    ….

}

In questo modo si cattura il contenuto del DataSource all’interno di un DatarowView, la cui propietà Row, tramite indice, consentirà di accedere al singolo dato ritornato.

Un adapter per la gridview … in puro CSS

20 Jun 2007 In: ASP e ASP.Net

In concomitanza con l'uscita del post di Alessandro, mi sono deciso a scaricare anche io gli ASP.NET 2.0 CSS Friendly Control Adapters perchè volevo "ritinteggiare" un paio di gridview all'ìnterno di un mio progetto.

Appena scaricata la "suite" di Microsoft la testo, e i pochi esempi lasciano ben sperare. Allora passo ad utilzzare l'adapter delle gridView.

Un paio di righe di codice, F5 … e … sorpresa … nell'HTML vedo ancora l'odioso tag table. Al che penso … avrò sbagliato qualcosa.

Provo a googlare in cerca di qualche esempio … ma niente … sempre che nessuno usi questi control adpater per fare stili in puro CSS (e pensare che io sono 3 anni abbondanti che ormai scrivo siti solo in CSS).

Rassegnato provo a dare un'occhiata al codice all'interno, ed effettivamente non mi sbagliavo. Per il gridview, l'adapter non fa altro che "incastonare" la tabella dentro ad un div, aggiungere dei tag intermedi che non sto ad elencare (potete guardare qui), ma fondamentalmente di CSS non c'è assolutamente niente.

Al che, rassegnato inizio a scrivere … ed ecco finalmente il mio ASP.Net Gridview Pure Css Adapter. E' in una sorta di beta … l'ho scritto appena ieri pomeriggio. Sicuramente è migliorabile … ma per il momento sembra funzionare. Con il tempo e con i suggerimenti sicuramente si può far tutto.

Buona gridview a tutti. 

Qualcosa di me

Mi chiamo Andrea Moro, sono un appassionato di informatica da quando avevo 8 anni e da quando mio padre mi regalò il C64.

Qualche anno più tardi, il mio primo pc e nel 1994 la prima esperienza con Internet, di cui mi sono subito innamorato e con cui oggi mando avanti la mia attività di Web Designing e posizionamento nei motori di ricerca.

Andrea Moro's profile on LinkedIn

Profilo Facebook di Andrea Moro


Sponsors


Google Friend