Accueil > Forum > > > > [C#][AS.NET] problème rendu custom web control
[C#][AS.NET] problème rendu custom web control
mardi 7 mars 2006 à 18:17:37 |
[C#][AS.NET] problème rendu custom web control

outcast_fr
|
Bonjour,
j'ai créé un custom web control comportant un zone de saisie éditable. On peut y ajouter du texte ou d'autres web controls via le designer par un simple glissé déposé.
Tout marche très bien dans le designer, je peux par exemple ajouter 2 boutons.
Le problème c'est que lorsque je lance ma page asp.net, j'ai bien le cadre (la couleur de fond) de mon custom web control mais aucun bouton n'est ajouté.
Savais-vous d'où peut venir le problème ? Merci
Voici le code :
| Code: |
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Web.UI; using System.Web.UI.Design; using System.Web.UI.Design.WebControls; using System.Web.UI.WebControls;
namespace Samples.ASPNet.ControlDesigners_CS { [Designer(typeof(MyMultiRegionControlDesigner)), ToolboxData("<{0}:MyMultiRegionControl runat=\"server\" width=\"200\"></{0}:MyMultiRegionControl>")] public class MyMultiRegionControl : CompositeControl { // Define the templates that represent 2 views on the control private ITemplate _view;
// Create persistable inner properties // for the two editable views [PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(null)] public virtual ITemplate View { get { return _view; } set { _view = value; } }
// Create a simple table with a row of two clickable, // readonly headers and a row with a single column, which // is the 'container' to which we'll be adding controls. protected override void CreateChildControls() { // Always start with a clean form Controls.Clear(); // Create a table using the control's declarative properties Table t = new Table(); t.CellSpacing = 1; t.BorderStyle = BorderStyle; t.Width = this.Width; t.Height = this.Height;
// Create the header row TableRow tr = new TableRow(); tr.HorizontalAlign = HorizontalAlign.Center; tr.BackColor = Color.LightBlue; tr.HorizontalAlign = HorizontalAlign.Center;
// This cell represents our content 'container' TableCell tc = new TableCell(); tc.Height = new Unit(20); tr.Cells.Add(tc);
t.Rows.Add(tr);
// Add the finished table to the Controls collection Controls.Add(t); }
}
//--------------------------------------------------------- // Region-based control designer for the above web control, // derived from CompositeControlDesigner. public class MyMultiRegionControlDesigner : CompositeControlDesigner { private MyMultiRegionControl myControl;
public override void Initialize(IComponent component) { base.Initialize(component); myControl = (MyMultiRegionControl)component; }
// Make this control resizeable on the design surface public override bool AllowResize { get { return true; } }
// Use the base to create child controls, then add region markers protected override void CreateChildControls() { base.CreateChildControls();
// Get a reference to the table, which is the first child control Table t = (Table)myControl.Controls[0];
// Add design time markers for each of the three regions if (t != null) { t.Rows[0].Cells[0].Attributes[DesignerRegion.DesignerRegionAttributeName] = "0"; } }
// Create the regions and design-time markup. Called by the designer host. public override String GetDesignTimeHtml(DesignerRegionCollection regions) { // Create an editable region and add it to the regions EditableDesignerRegion editableRegion = new EditableDesignerRegion(this, "Content", false); regions.Add(editableRegion);
// Use the base class to render the markup return base.GetDesignTimeHtml(); }
// Get the content string for the selected region. Called by the designer host? public override string GetEditableDesignerRegionContent(EditableDesignerRegion region) { // Get a reference to the designer host IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost)); if (host != null) { ITemplate template = myControl.View;
// Persist the template in the design host if (template != null) return ControlPersister.PersistTemplate(template, host); }
return String.Empty; }
// Create a template from the content string and // put it in the selected view. public override void SetEditableDesignerRegionContent(EditableDesignerRegion region, string content) { if (content == null) return;
// Get a reference to the designer host IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost)); if (host != null) { // Create a template from the content string ITemplate template = ControlParser.ParseTemplate(host, content);
if (template != null) { myControl.View = template; } } } } } |
|
|
mardi 7 mars 2006 à 19:01:49 |
Re : [C#][AS.NET] problème rendu custom web control

jesusonline
|
Bonjour si on regarde seulement ton controle : public class MyMultiRegionControl : CompositeControl { // Define the templates that represent 2 views on the control private ITemplate _view;
// Create persistable inner properties // for the two editable views [PersistenceMode(PersistenceMode.InnerProperty), DefaultValue(null)] public virtual ITemplate View { get { return _view; } set { _view = value; } }
// Create a simple table with a row of two clickable, // readonly headers and a row with a single column, which // is the 'container' to which we'll be adding controls. protected override void CreateChildControls() { // Always start with a clean form Controls.Clear(); // Create a table using the control's declarative properties Table t = new Table(); t.CellSpacing = 1; t.BorderStyle = BorderStyle; t.Width = this.Width; t.Height = this.Height;
// Create the header row TableRow tr = new TableRow(); tr.HorizontalAlign = HorizontalAlign.Center; tr.BackColor = Color.LightBlue; tr.HorizontalAlign = HorizontalAlign.Center;
// This cell represents our content 'container' TableCell tc = new TableCell(); tc.Height = new Unit(20); tr.Cells.Add(tc);
t.Rows.Add(tr);
// Add the finished table to the Controls collection Controls.Add(t); }
}
on ne voit nul part que tu rajoutes tes boutons. Avant de faire le mode design je finit déjà le mode normal ;) le mode design vient ensuite ... c'est souvent beaucoup plus facile car en plus dans 80% des cas le mode design ne sert jamais... (en tout cas pas pour moi)
Cyril - MVS - MCP ASP
|
|
mercredi 8 mars 2006 à 10:01:26 |
Re : [C#][AS.NET] problème rendu custom web control

outcast_fr
|
C'est normal que l'on ne voit pas que j'ajoute les boutons, puisqu'ils sont ajoutés en mode design, dynamiquement (par un glisser/déposer). Je parlais de boutons pour l'exemple, mais on peut y ajouter n'importe quels web controls (ou custom webcontrols). Par contre sur la page HTML rendu, il n'y a aucun bouton (ou autre) ajouté.
Le problème c'est que si je place une méthode Render, je n'ai plus rien qui s'affiche dans le mode design (ou alors je ne sais pas m'en servir) hormis ce que j'ai écrit dans la méthode Render.
Ce que j'aimerais mais que je ne sais pas trop comment faire c'est générer les "ChildControls" (= ceux que l'ont ajoute dynamiquement par le designer).
|
|
mercredi 8 mars 2006 à 17:30:55 |
Re : [C#][AS.NET] problème rendu custom web control

outcast_fr
|
Réponse acceptée !
Bon ben à force de chercher et rechercher, j'ai trouvé la solution à mon problème en me basant sur ces deux articles de la msdn.
Je ne sais pas si c'est la meilleur solution, mais elle a le mérite de fonctionner.
Ne me demandez pas par contre des détails sur le fonctionnement exact de "ma" solution, car moi-même je me demande parfois comment j'ai pu le faire (en rouge les mises à jours par rapport au code précédent)
| Code: |
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Web.UI; using System.Web.UI.Design; using System.Web.UI.Design.WebControls; using System.Web.UI.WebControls;
namespace Samples.ASPNet.ControlDesigners_CS { [Designer(typeof(MyMultiRegionControlDesigner)), ToolboxData("<{0}:MyMultiRegionControl runat=\"server\" width=\"200\"></{0}:MyMultiRegionControl>")] public class MyMultiRegionControl : CompositeControl { private Control myTemplateContainer;
// Define the templates that represent 2 views on the control private ITemplate _view;
// Create persistable inner properties // for the two editable views [DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(ViewContainer))] public virtual ITemplate MyView { get { return _view; } set { _view = value; } }
// Create a simple table with a row of two clickable, // readonly headers and a row with a single column, which // is the 'container' to which we'll be adding controls. protected override void CreateChildControls() { // Always start with a clean form Controls.Clear(); // Create a table using the control's declarative properties Table t = new Table(); t.CellSpacing = 1; t.BorderStyle = BorderStyle; t.Width = this.Width; t.Height = this.Height;
// Create the header row TableRow tr = new TableRow(); tr.HorizontalAlign = HorizontalAlign.Center; tr.BackColor = Color.LightBlue;
// This cell represents our content 'container' TableCell tc = new TableCell(); tc.Height = new Unit(20);
//---------------------------------------------------- //---------------------------------------------------- if (MyView != null) { myTemplateContainer = new ViewContainer(this); MyView.InstantiateIn(myTemplateContainer); tc.Controls.Add(myTemplateContainer); } //---------------------------------------------------- //----------------------------------------------------
tr.Cells.Add(tc); t.Rows.Add(tr);
// Add the finished table to the Controls collection Controls.Add(t);
}
protected override void OnDataBinding(EventArgs e) { EnsureChildControls(); base.OnDataBinding(e); } }
public class ViewContainer : Control, INamingContainer { private MyMultiRegionControl parent; public ViewContainer(MyMultiRegionControl parent) { this.parent = parent; } }
//--------------------------------------------------------- // Region-based control designer for the above web control, // derived from CompositeControlDesigner. public class MyMultiRegionControlDesigner : CompositeControlDesigner { private MyMultiRegionControl myControl;
public override void Initialize(IComponent component) { base.Initialize(component); myControl = (MyMultiRegionControl)component; }
// Make this control resizeable on the design surface public override bool AllowResize { get { return true; } }
// Use the base to create child controls, then add region markers protected override void CreateChildControls() { base.CreateChildControls();
// Get a reference to the table, which is the first child control Table t = (Table)myControl.Controls[0];
// Add design time markers for each of the three regions if (t != null) { t.Rows[0].Cells[0].Attributes[DesignerRegion.DesignerRegionAttributeName] = "0"; } }
// Create the regions and design-time markup. Called by the designer host. public override String GetDesignTimeHtml(DesignerRegionCollection regions) { // Create an editable region and add it to the regions EditableDesignerRegion editableRegion = new EditableDesignerRegion(this, "Content", false); regions.Add(editableRegion);
// Use the base class to render the markup return base.GetDesignTimeHtml(); }
// Get the content string for the selected region. Called by the designer host? public override string GetEditableDesignerRegionContent(EditableDesignerRegion region) { // Get a reference to the designer host IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost)); if (host != null) { ITemplate template = myControl.MyView;
// Persist the template in the design host if (template != null) return ControlPersister.PersistTemplate(template, host); }
return String.Empty; }
// Create a template from the content string and // put it in the selected view. public override void SetEditableDesignerRegionContent(EditableDesignerRegion region, string content) { if (content == null) return;
// Get a reference to the designer host IDesignerHost host = (IDesignerHost)Component.Site.GetService(typeof(IDesignerHost)); if (host != null) { // Create a template from the content string ITemplate template = ControlParser.ParseTemplate(host, content);
if (template != null) { myControl.MyView = template; } } } } } | Vous pouvez effectuer un copier/coller du code et le générer directement.
Si vous avez des suggestions ou des améliorations à proposer, n'hésitez pas !
|
|
Cette discussion est classée dans : web, control, using, host, create
Répondre à ce message
Sujets en rapport avec ce message
Pb de datagrid->pour faire un panier ASP.net C# [ par fabrice83 ]
fab83je suis en BTS est mon projet est de réaliser un site de vente g un pb avec mon panier .Voici mon code j'ai une datgrid1qui represente mon catal
Control creer dynamiquement [ par alk ]
Alors voila je declare un System.Web.UI.Controlsdans un fichier aspx.cs et je souhaite le voir apparaitre sur ma WebForms cependant je recois une erre
[.Net] Différence Includes / Web User Control [ par cbu ]
Yop yop à tous,bon y aurait il un petit gars ou une petite gazelle qui pourrait me dire si on utilise toujours les includes en .Net, si c'est propre e
appel de fonction :( [ par yafuka ]
bonjour a tous et merci d'avance.Mon probleme est bien simple.je declare une classe page1_2 dans un fichier page1_2.cs (voir ci dessous) contenant un
SQL SERVER [ par rabbiwan ]
bonjourj'ai un petit problème de connexionj'arrive a me connecter sur mon server avec un petit programme que vous pouvez trouver a http://www.aspfr.co
problème de décompression de fichier zip- les fichiers restent ouverts [ par mohamed_bn ]
med belhassen j'ai utilisé ce petit programme que j'ai trouvé sur ce site dans mon application web. il permet de décompresser les fichiers zips.mais l
Web user control dynamique [ par systemic_anomaly ]
Bonjour à tous.Je débarque dans l'asp.net et j'ai fais un web user control qui me sert de menu vers des pages différentes. J'aimerais pouvoir ajouter
procédure pour importer un ascx depuis le code behind [ par tomtom41 ]
voila ca fait 3h que je suis dessus et je n'y arrive pas quelle est la procédure pour importer un ascx afin de puis utiliser le type d
Image en arrier plan dans Web user Control [ par edokt ]
Bonjour tout le monde J'ai un petit problem Je veux mettre une image en arrire plan dans un Web user control Qq1 peut me dire comment il faut faire
web user control vs 2005 [ par chocobob ]
Bonjour, je trvavaille avec visual studio 2005 beta 2 j ai creer un projet web avec mon index.aspx ans asp.net2 j aimerai comme avec le 2003 creer
Livres en rapport
|
Derniers Blogs
[TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES[TECHDAYS 2012] SESSION WEBMATRIX 2 : LE COUTEAU SUISSE GRATUIT POUR VOS DéVELOPPEMENTS WEB - SLIDES par gpommier
Suite à la session que j'ai présenté sur WebMatrix 2, vous pouvez trouver les slides ici, ainsi que les démos en packages nuget : démos1 et démos2 J'en profite pour remercier chaleureusement tous ceux qui sont venus très nombreux à cette sess...
Cliquez pour lire la suite de l'article par gpommier [SHAREPOINT] LES SESSIONS TECHDAYS 2012.[SHAREPOINT] LES SESSIONS TECHDAYS 2012. par Patrick Guimonet
Voici donc pour ceux qui n'ont pas pu venir, ou ceux qui n'ont pas pu toutes les suivre la liste des sessions SharePoint aux TechDays 2012, que je mettrais à jour dès que les liens des vidéo seront disponibles. Ou ici : http...
Cliquez pour lire la suite de l'article par Patrick Guimonet TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3TECHDAYS PARIS 2012 : SESSION PLEINIèRE JOUR 3 par ROMELARD Fabrice
Speaker: Bernard Ourghanlian Cette session est comme chaque jour transmise en live par BrainSonic, et j'ai donc suivi cette troisième pleinière par ce moyen sur mon iPad . Elle est dédiée comme chaque année à la mise en perspective de l'é...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE !MISHRA READER : UN LECTEUR RSS TRèS ZUNE STYLE EN OPEN SOURCE ! par Vko
Hier durant une session dédiée aux Techdays 2012, j'ai eu le plaisir d'annoncer la sortie de la Béta 2 de Mishra Reader. C'est quoi ? Pour les utilisateurs, c'est une vraie expérience de lecture de flux RSS sur Windows. Rien à voir avec les produit...
Cliquez pour lire la suite de l'article par Vko [FRAMEWORK 4] LES TASKS ET LE THREAD UI[FRAMEWORK 4] LES TASKS ET LE THREAD UI par fathi
Je viens de passer quelques temps au TechDay's et j'ai pu voir pas mal de session intéressante. Par contre une chose m'a un peu étonné lors de certaines de ces sessions qui abordaient les améliorations du framework .NET (donc le 4.5) : en gros, bea...
Cliquez pour lire la suite de l'article par fathi
Forum
RE : FORMULAIRERE : FORMULAIRE par Megafan
Cliquez pour lire la suite par Megafan FORMULAIREFORMULAIRE par ap24dp
Cliquez pour lire la suite par ap24dp
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|