C++ C++ C# C# ASP.NET Security ASP.NET Security ASM ASM Скачать Скачать Поиск Поиск Хостинг Хостинг  
  Программа для работы с LPT портом...
Язык: .NET — ©Alexey...
  "ASP.NET Atlas" – AJAX в исполнении Micro...
Язык: .NET — ©legigor@mail.ru...
  "Невытесняющая" Многопоточность...
Язык: C/C++ — ©...
  Update World C++: Сборник GPL QT исходников
  Весь сайт целиком можно загрузить по ссылкам из раздела Скачать
Дебетовая карта Home Credit [CPS] RU

 Dynamically Adding Custom User Controls to a Web Part Catalog Zone / User Controls / ASP. NET

Sample Image


Welcome! This article shows how you can add custom user controls to your web page, dynamically, at run time. Adding custom user controls to a web page can be done by using web parts. As shown in the figure above, the page is divided into several partitions, and we have some zones called WebPartZone1 and WebPartZone2. These are the zones where you can place your custom control web parts. Above that, we have a Browse button to browse and locate the user control that you wish to add on your web page, from your system, to upload to the server. We also have a drop down list box that enables selection of the mode in which you wish to view the page. There are four different modes in which you can view the page, they are Browse, Edit, Catalog, and Design. We shall learn about these modes of display, later in this article. Now, assume you have a Calendar control on your system (even if you don't have, we will see how to create one), and you wish to add it to the web page dynamically. We shall see how this is achieved here.

Some basics

Well, I have already talked about web parts, WebPartZones, and Display modes.. If you are new to all this, definitely, it may sound Greek and Latin. So let me brush up some basics here. First of all, you need to know a little bit of programming in ASP.NET and some fundamentals of C#. If you visit the site, http://my.yahoo.com/, you will come across snippets of information provided on the page, and the best part is you can customize the look and feel of the page according to your needs. This customization is provided by means of what are called WebParts. You can choose what information is displayed on that page and where it should be displayed.

Now, what are web part zones? These zones are nothing but placeholders where you can place your web parts. The page can be divided into any number of zones, and you can place web parts onto whichever zones you want to. Now, coming to the modes of display - Browse mode is the normal mode of display. When you visit a web page, you cannot edit any content of the page, but will only be able to view the contents. This default mode of display is called Browse display mode. In Design display mode , you can move web parts from one zone to another by simply dragging and dropping it to the zones. It's that simple! CatalogDisplay mode is something different. It displays a catalog zone (not shown on the figure as the page is currently in Design display mode as could be seen from the drop down list box) where you have a list of web parts which you can add to the web part zones. A catalog zone may have a declarative catalog part - this contains the user controls that you have added to the catalog zone, a page catalog part - it contains the web parts that were on your page initially, but now closed and not shown on the page, and an import catalog part - which allows you to import web parts to your page dynamically.

Note: We won't be using this import catalog part to import user controls because it requires files with extension *.webpart, but user controls have an extension *.ascx. So, if you try to import a user control using this import catalog part, it won't work!! Then, there is something called editor zone using which you can edit the properties of the webpart such as appearance, behavior etc., but that is beyond the scope of discussion in this article.

If you are thinking about how to add these to your web page, don't worry, it's all available as a drag drop feature in your toolbox in Visual Studio 2005 (shown in the figure adjacent). Well, I guess that would have given you some insight into web parts. So, let's get ready to take off!

Designing your page

Before you start adding the web part zones to your page, you should first add something called the WebPartManager. As the name suggests, it takes full care of managing the web parts on your page. The code for the web part manager is pretty simple, and it looks like this:

<html xmlns ="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Home Page</title>
<body bgcolor="lightsteelblue">
<form id="form1" runat="server">
<asp:WebPartManager ID="WebPartManager1" 
         Runat="Server" /></form>

I have added two web part zones to the page, and I have also added a catalog zone with a PageCatalogPart. I have also added provision for uploading files to the server. Note that I have made use of the HTML input file button to upload files, as it makes my job pretty easier. Then, I have a drop down list box showing the display modes so that by selecting one of them, I can switch between the modes. The full code for the default.aspx page can be downloaded from the Zip file attached. After designing your page, now it's time to write the code-behind.

Writing your own custom control

The process of writing your own custom control is very easy. Click on Add New Item on your project window, and choose Custom User Control. It will have an extension *.ascx. Now, a new page opens up, and you can place any control that you want to that best suits your needs. For simplicity, just place a Calendar control. Now, switch to the source view, and copy the source code and paste it in Notepad, and save it as, say, cal.ascx. That's it, you have a user control at your hand. Now, after running the web page, you can upload the user control to your server and see how it works on the web.

Writing the code-behind

The code for switching between the modes is pretty simple:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    switch (DropDownList1.SelectedValue)
    case "Browse":
        WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
    case "Design":
        WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
    case "Edit":
        WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
    case "Catalog":
        WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;

To upload files to your page dynamically, you need to write some piece of code behind the Upload button. Note that the Upload button should also take care of uploading files with the names that already exist on the server. Suppose you already have a file cal.ascx on your server, and still, if you upload another file with the same name, the older file will be overwritten with the new file. To avoid that from happening, we include a small piece of code to prefix an underscore (_) before the name of the file until we arrive at a unique filename. The code behind the Upload button is given below:

protected void Upload_Click(object sender, EventArgs e)
    string strFileName = MyFile.PostedFile.FileName;
    strFName = System.IO.Path.GetFileName(strFileName);
    Response.Write("upload : " + strFName);
    while (System .IO.File .Exists ("D:\\intern\\webapp" + 
           "\\DynamicWebPart\\DynamicWebPart\\" + strFName))
    strFName = "_" + strFName; 
        MyFile.PostedFile.SaveAs("D:\\intern\\webapp\\" + 
               "DynamicWebPart\\DynamicWebPart\\" + strFName);
        Response.Write("File Upload Successful");
    catch (Exception e1)
        Response.Write("Exception : " + e1);
    Label1.Visible = true;
    TextBox1.Visible = true;
    Button1.Visible = true;

Note that the path that I have given will save the file onto the directory of the file system specified. In your system, please modify the path as to where you need to store the uploaded file. The while loop takes care of the unique naming of uploaded files. Once the file is uploaded, the next thing to do is to add the uploaded user control to the catalog zone of your web page. Formally, the web parts should be added only to the declarative catalog part, but even after hours of trying to do this, I couldn't figure out how to do it at run-time. So I placed the web part onto one of the web part zones, and closed the web part programmatically (closing the web part places it onto the page catalog part automatically). So don't be perplexed that the uploaded file is not seen on your page. You now switch over to the catalog display mode, and you can see your web part on the PageCatalogPart, which can be added to the web part zone you wish to. The code that achieves this is given below:

protected void Button1_Click(objectsender, EventArgs e)
        Control control = LoadControl(strFName);
        control.ID = "control";
        WebPart myWebPart = WebPartManager1.CreateWebPart(control);
        myWebPart.Title = TextBox1.Text.ToString ();
        WebPart newPart = WebPartManager1.AddWebPart(myWebPart, 
                          WebPartManager1.Zones[0], 0);
        if(WebPartManager1.WebParts .Contains (newPart ))
    catch (HttpExceptione2)
        Response.Write("Exception e2 : " + e2);
    Label1.Visible = falsefalse;
    Button1.Visible = false;

Now, your web page is ready and fully functional. But there are some other key aspects to know before you get into trouble.

Points of interest

What if you want to reset all the changes that you have made to your page in the process of customizing it? What if you want the page to look like how it was during the design phase? There is a solution for this... The Reset button. No, not the Reset button you have on your HTML controls. This is an ASP button with the following code-behind:

protected void LinkButton1_Click(object sender, EventArgs e)

Another important thing to note is that, chances are that you may receive an error message stating that "Under Default conditions, SQL Server 2005 will not allow remote connections". If you get that error message, don't get perplexed that you have not used any database but why is that the error message is coming. It is because, you are personalizing the page, and this personalization is provided for every user who accesses this web page. So the server uses a database to store the changes or the customizations you have done to the page, under your user name or user ID. Hence comes the need of the database. When you get that error message, follow the link that tells you what is to be done to rectify the problem.

That completes this article. Feel free to post your comments... I'll be more than glad to receive your remarks and suggestions!

Дебетовая карта Home Credit [CPS] RU