Andrea Painelli's Blog


"You shouldn't compare yourself to the best others can do but to the best you can do"
Ora e Data
Calendario
giugno 2025
lmmgvsd
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456
Archivio Posts
Anno 2007

Modificare il contenuto delle celle di Un asp:Calendar

E' utile per selezionare date, ma anche per mostrare eventualmente dati estratti da un database.
L'esempio di oggi rientra nell'ultima tipologia ed anche se alla fine mostra solo dei link in base al valore contenuto in un Array (precedentemente popolato ad esempio a partire da un database), può semplicemente essere riciclato per fini differenti, ad esempio per mostrare le presenze di un dipendente in un mese.
Il codice si basa dunque su un Array bidimensionale, composta dalla prima colonna che indica il mese e dalla seconda che indica il giorno.
Alla fine è sufficiente intercettare l'evento DayRender del Calendar (che si verifica ogni volta che un giorno è creato) e scrivere all'interno della cella quello che ci pare.
<SCRIPT runat="SERVER" language="C#">
private string[,] myContent = new string[13, 32];

private void Page_Load(object sender, System.EventArgs e)
{
// estrazione dati da db

// creiamo alcuni inserimenti a caso

myContent[DateTime.Today.Month, DateTime.Today.Day] = "http://www.aspitalia.com/";
myContent[12, 12] = "http://whideyday.aspitalia.com/";
myContent[DateTime.Today.Month, 28] = "http://forum.aspitalia.com/";
}

protected void cal_DayRender(object sender,DayRenderEventArgs e)
{
// disattivo la selezione di tutti i giorni

e.Day.IsSelectable = false;

// verifico che nell'Array ci sia qualcosa

string Cont = null;
DateTime dt = DateTime.Parse(e.Day.Date.ToString());
Cont = myContent[Convert.ToInt32(dt.Month.ToString()), Convert.ToInt32(dt.Day.ToString())];

if (Cont!= null)
{
  // rimuovo tutti i controls esistenti

  for (int j = 0; j<=e.Cell.Controls.Count; j++)
  {
  e.Cell.Controls.RemoveAt(j);
  }
 
  // cambio colore di sfondo

  e.Cell.BackColor = System.Drawing.Color.Red;

  // creo una nuova label e l'aggiungo alla cella

  Label lblContent = new Label();
  lblContent.Text = "<a href=\"" + Cont + "\">" + e.Day.DayNumberText + "</a>";
  e.Cell.Controls.Add (lblContent);
}
}

</SCRIPT>

<form runat="server">
<asp:calendar id="cal" runat="server" onDayRender="cal_DayRender" enableviestate="false"/>
</form>
Categoria: dotNET
giovedì, 02 ago 2007 Ore. 09.56


Dott. Andrea Painelli (classe '83)
Statistiche
  • Views Home Page: 6.180
  • Views Posts: 16.587
  • Views Gallerie: 68
  • n° Posts: 10
  • n° Commenti: 3
Copyright © 2002-2007 - Blogs 2.0
dotNetHell.it | Home Page Blogs
ASP.NET 2.0 Windows 2003