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
QUELQUES TRUCS INTéRESSANTS (05/09/2010)QUELQUES TRUCS INTéRESSANTS (05/09/2010) par coq
Cette fois-ci : .NET Debug / Performance Sécurité SQL Server .NET Determining if a type is defined in the .NET Framework (blog de Scott Dorman) Ha tiens, je n'avais jamais vraiment pensé à utiliser le jeton de clé publique...
Cliquez pour lire la suite de l'article par coq ENUMERABLECOLLECTIONENUMERABLECOLLECTION par Matthieu MEZIL
Prenons le scénario suivant. On utilise MVVM. On a les deux classes suivantes dans le model : public class Child { } public class Parent { private ObservableCollection < Child > _children; public ObservableCollection < Child > Children { get {...
Cliquez pour lire la suite de l'article par Matthieu MEZIL [HS] CHROME 6 + MOI = COUP DE GUEULE ![HS] CHROME 6 + MOI = COUP DE GUEULE ! par JeremyJeanson
Attention, le poste qui suit n'est pas la complainte d'une personne : Qui n'aime pas Chrome. D'un anti Google. D'un développeur qui a un poil énorme dans la main. Ceux qui me fréquentent savent que je change de navigateur favori tous les 2 ou 3 mois afin ...
Cliquez pour lire la suite de l'article par JeremyJeanson [WP7] UTILISER UN WRAPPANEL DANS UNE APPLICATION WINDOWS PHONE 7[WP7] UTILISER UN WRAPPANEL DANS UNE APPLICATION WINDOWS PHONE 7 par Audrey
Lors de la réalisation de ma 2ème application Windows Phone 7, j'ai souhaité utiliser un WrapPanel pour afficher plusieurs photos. Mais le contrôle WrapPanel ne fait pas parti de la liste des contrôles inclus dans le SDK de la version Beta des outils pour...
Cliquez pour lire la suite de l'article par Audrey [WP7] BESOIN D'AVOIR DES DONNéES EN CACHE[WP7] BESOIN D'AVOIR DES DONNéES EN CACHE par Nicolas
Les développeurs ASP.NET ont l'habitude de mettre des données en cache pour éviter de requêter a chaque fois la base de données. Et il est toujours utilie de penser que vos utilisateurs mobiles n'ont pas troujours une super connexion 3G/WIFI et un for...
Cliquez pour lire la suite de l'article par Nicolas
Logiciels
WebLogAndPass (1.0.0)WEBLOGANDPASS (1.0.0)WebLogAndPass est un logiciel permettant de mémoriser vos sites préférés et pour chacun d'entre-e... Cliquez pour télécharger WebLogAndPass uTorrent (2.0.4)UTORRENT (2.0.4)C'est un client BitTorrent très puissant et très performant. Comme son nom l'indique, uTorrent (m... Cliquez pour télécharger uTorrent Bureau de Gestion - ERP Devis Facturation (2.02)BUREAU DE GESTION - ERP DEVIS FACTURATION (2.02)- Version gratuite du 10/06/2010
Le Bureau de Gestion est un logiciel dédié à la gestion de l'en... Cliquez pour télécharger Bureau de Gestion - ERP Devis Facturation 4Videosoft Transfert iPod Mac (3.2.08)4VIDEOSOFT TRANSFERT IPOD MAC (3.2.08)4Videosoft Transfert iPod-Mac caractérise principalement à transférer les fichiers iPod vers Mac.... Cliquez pour télécharger 4Videosoft Transfert iPod Mac 4Videosoft HD Convertisseur (3.3.08)4VIDEOSOFT HD CONVERTISSEUR (3.3.08)Etant le meilleur HD Vidéo Convertisseur, 4Videosoft HD Convertisseur, vous pouvez regarder la vi... Cliquez pour télécharger 4Videosoft HD Convertisseur
|