Friday, August 29, 2008

Creating the List of Drives in the TreeView Control

you can see the code that uses the static GeTDrives method of the DriveInfo class to get a list of all installed drives, then iterates through them. For each fixed, formatted, and available (ready) drive, the code creates a new node containing details of the drive. It then sets the ImageUrl to the custom image, specifies that clicking this node will cause a postback that executes the "populate on demand" event handler, and adds the node to the treeView.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeView.aspx.cs" Inherits="TreeView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:TreeView ID="treeDir" runat="Server">
           </asp:TreeView>
           <asp:Label ID="lblError" runat="Server"></asp:Label>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class TreeView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateTreeView();

    }
    private void CreateTreeView()
    {
        treeDir.Nodes.Clear();
        TreeNode node = new TreeNode("My Computer", "Root");
        node.SelectAction = TreeNodeSelectAction.None;
        node.Expanded = true;
        treeDir.Nodes.Add(node);
        try
        {
            // get a list of installed drives
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo d in allDrives)
            {
                // only include fixed drives that are ready
                if (d.DriveType == DriveType.Fixed && d.IsReady)
                {
                    // create text for the TreeView to display
                    StringBuilder sb = new StringBuilder();
                    sb.Append(d.Name.Substring(0, 2));
                    sb.Append(" ");
                    sb.Append(d.VolumeLabel);
                    sb.Append(" (");
                    sb.Append(d.DriveFormat);
                    sb.Append(") ");
                    Double space = d.AvailableFreeSpace / 1024 / 1024;
                    sb.Append(space.ToString("#,###,###,##0"));
                    sb.Append(" MB available");
                    String theName = sb.ToString();
                    String theValue = d.Name;
                    // add a node to the TreeView with "drive" image
                    TreeNode child = new TreeNode(theName, theValue);
                    child.ImageUrl = "images/icon_drive.gif";
                    // specify postback for populating child nodes
                    child.SelectAction = TreeNodeSelectAction.Expand;
                    child.PopulateOnDemand = true;
                    node.ChildNodes.Add(child);
                }
            }
        }
        catch (Exception ex)
        {
            lblError.Text = "ERROR: " + ex.Message + "<p />";
        }
    }

}

Thursday, August 28, 2008

How to: Create Templated ASP.NET User Controls

Another feature that is often ignored with user controls, but that can be very useful, is the template. Templates are often associated with server controls and are an important part of both the DataList and the Repeater controls. However, their usefulness is not limited to server controls. Templates, however, allow us to provide a means for the page designer to supply HTML content that will be rendered within our control. Templates allow our user controls to be more flexible because they are used across pages within our application.

1. In the .ascx file, add an ASP.NET PlaceHolder control where you want the template to appear.

2. In the user control's code, implement a property of type ITemplate.

3. Define a server control class that implements the INamingContainer interface as a container in which to create an instance of the template. This is called the template's naming container.

4. Apply the TemplateContainerAttribute to the property that implements ITemplate and pass the type of the template's naming container as the argument to the attribute's constructor.

5. In the control's Init method, repeat the following steps one or more times:

o Create an instance of the naming container class.

o Create an instance of the template in the naming container.

o Add the naming container instance to the Controls property of the PlaceHolder server control.

SupportTemplates.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SupportTemplates.ascx.cs"
Inherits="SupportTemplates" %>
<table>
<tr>
   <td>
       <asp:PlaceHolder ID="headerContainer" runat="server"></asp:PlaceHolder>
   </td>
</tr>
<tr>
   <td>
       <i>This is the static content that always appears on the control</i><br />
       <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
   </td>
</tr>
<tr>
   <td>
       <asp:PlaceHolder ID="footerContainer" runat="server"></asp:PlaceHolder>
   </td>
</tr>
</table>
SupportTemplates.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;
public partial class SupportTemplates : System.Web.UI.UserControl
{
private ITemplate messageTemplate = null;

[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate MessageTemplate
{
    get
    {
        return messageTemplate;
    }
    set
    {
        messageTemplate = value;
    }
}
protected ITemplate _footerTemplate;
protected ITemplate _headerTemplate;
[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate FooterTemplate
{
    get { return _footerTemplate; }
    set { _footerTemplate = value; }
}
[TemplateContainer(typeof(MessageContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate HeaderTemplate
{
    get { return _headerTemplate; }
    set { _headerTemplate = value; }
}

private void Page_PreRender(object sender, System.EventArgs e)
{
    if (_headerTemplate != null)
        _headerTemplate.InstantiateIn(headerContainer);
    if (_footerTemplate != null)
        _footerTemplate.InstantiateIn(footerContainer);
}

void Page_Init()
{
    if (messageTemplate != null)
    {
        String[] fruits = { "apple", "orange", "banana", "pineapple" };
        for (int i = 0; i < 4; i++)
        {
            MessageContainer container = new MessageContainer(i, fruits[i]);
            messageTemplate.InstantiateIn(container);
            PlaceHolder1.Controls.Add(container);
        }
    }
}

public class MessageContainer : Control, INamingContainer
{
    private int m_index;
    private String m_message;
    internal MessageContainer(int index, String message)
    {
        m_index = index;
        m_message = message;
    }
    public int Index
    {
        get
        {
            return m_index;
        }
    }
    public String Message
    {
        get
        {
            return m_message;
        }
    }
}


}
How To Use
TemplateDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TemplateDemo.aspx.cs" Inherits="Template" %>

<%@ Register Src="SupportTemplates.ascx" TagName="SupportTemplates" TagPrefix="uc2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Untitled Page</title>
</head>
<body>
 <form id="form1" runat="server">
     <div>
         <uc2:SupportTemplates ID="SupportTemplates1" runat="server">
             <HeaderTemplate>
                 <b>This is Header</b>
             </HeaderTemplate>
             <MessageTemplate>
                 Index:
                 <asp:Label runat="server" ID="Label1" Text='<%# Container.Index %>' />
                 <br />
                 Message:
                 <asp:Label runat="server" ID="Label2" Text='<%# Container.Message %>' />
                 <hr />
             </MessageTemplate>
             <FooterTemplate>
                 <b>This Is Footer</b>
             </FooterTemplate>
         </uc2:SupportTemplates>
     </div>
 </form>
</body>
</html>
TemplateDemo.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Template : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      this.DataBind();
  }
}

How To Display vertical record in GridView

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VerticalData.aspx.cs" Inherits="VerticalData" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server">
           </asp:GridView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class VerticalData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            GridView1.DataSource = GoDoReShape(_sampleData);
            GridView1.DataBind();
        }

    }
    public DataTable _sampleData
    {
        get
        {
            DataTable dt = (DataTable)Session["DataTable"];
            if (dt == null)
            {
                dt = new DataTable();
                dt.Columns.Add(new DataColumn("ID", typeof(string)));
                dt.Columns.Add(new DataColumn("Item", typeof(string)));
                dt.Columns.Add(new DataColumn("Price", typeof(string)));


                dt.Rows.Add(new object[] { "1", "Product1", "12.43", });
                dt.Rows.Add(new object[] { "2", "Product2", "11.43", });
                dt.Rows.Add(new object[] { "3", "Product3", "13.43", });
                Session["DataTable"] = dt;
            }
            return dt;
        }
        set
        {
            Session["DataTable"] = value;
        }
    }
    public DataTable GoDoReShape(DataTable dt)
    {
        DataTable NewDt = new DataTable();
        //Create Two Columns with names "ColumnName" and "Value"
        //ColumnName -> Displays all ColumnNames
        //Value -> Displays ColumnData
        NewDt.Columns.Add("ColumnName");
        NewDt.Columns.Add("Value");
        foreach (DataRow dr in dt.Rows)
        {
            foreach (System.Data.DataColumn dcol in dt.Columns)
            {
                //Declare Array
                string[] MyArray ={ dcol.ColumnName.ToString(), dr[dcol.ColumnName.ToString()].ToString() };
                NewDt.Rows.Add(MyArray);
            }
        }
        return NewDt;
    }



}

Using the RegisterArrayDeclaration Method

Let's create a simple Web page to demonstrate the RegisterArrayDeclaration method. This page provides a slide show where the client-side JavaScript changes the image. In this example, we will search a specified folder on the server and load the names of all the images in a JavaScript array. We will also provide two buttons, one for showing the next image from the list and another for showing the previous one
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ArrayDeclaration.aspx.cs"
    Inherits="ArrayDeclaration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript">
      var curPic = 0;

      function processPrevious()
      {
            if (curPic==0)
            {
                  curPic=Pictures.length - 1;
            }
            else
            {
                  curPic--;
            }
            document.getElementById('<%=myPicture.ClientID%>').src=Pictures[curPic];
      }

      function processNext()
      {
            if (curPic==Pictures.length -1)
            {
                  curPic=0;
            }
            else
            {
                  curPic++;
            }
            document.getElementById('<%=myPicture.ClientID%>').src=Pictures[curPic];
      }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table border="1">
                <tr>
                    <td>
                        <asp:Image ID="myPicture" runat="Server" Height="500px" Width="600px" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="BackButton" runat="Server" Text="Back" />
                        <asp:Button ID="NextButton" runat="Server" Text="Previous" />
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class ArrayDeclaration : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {

           StringBuilder imageArray = new StringBuilder();
           // The GetImageArray method searches the Images
           // folder and returns a JavaScript array declaration
           // for all files contained in the folder.

           imageArray = GetImageArray("Image");
            // Once we have the array declaration, we simply add it
           // to the page by using the RegisterArrayDeclaration method.
           // The name of the JavaScript array will be Pictures,
           // as specified in the first parameter.

           ClientScript.RegisterArrayDeclaration("Pictures", imageArray.ToString());
           // Wiring the Back button's click event to
           // the processPrevious function. Make sure to
           // return false in order to disable post-back operation.

           BackButton.Attributes.Add("onClick", "processPrevious();return false;");

                //Wiring the Next button's click event to
                // the processNext function. Make sure to
                // return false in order to disable post-back operation.

           NextButton.Attributes.Add("onClick", "processNext();return false;");

       }
   }
    // This function receives a folder name and returns a
    //   JavaScript array declaration containing names of all files
    //  from the folder.

   protected StringBuilder GetImageArray(string folderName)
   {


       string Path;
       DirectoryInfo Folder;

       FileInfo[] Images;
       StringBuilder ImageArray = new StringBuilder();

       Path = Request.PhysicalApplicationPath + folderName;
       Folder = new DirectoryInfo(Path);
       Images = Folder.GetFiles();

       // Looping through all files in the folder and generating
       // a JavaScript array declaration.
       foreach (FileInfo Image in Images)
       {
           ImageArray.AppendFormat("'{0}/{1}',", folderName, Image.Name);
       }

       // Removing the unwanted last comma.
       ImageArray.Remove(ImageArray.Length - 1, 1);

       return ImageArray;
   }


}

How to hide and show data in the DataList?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataListHide.aspx.cs" Inherits="DataListHide" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:DataList runat="server"  ID="Datalist1" Font-Size="10pt"
               Font-Name="Verdana" OnItemCommand="Datalist1_ItemCommand">
               <ItemTemplate>
                   <asp:LinkButton Style="text-decoration: none" runat="server" ID="btnDetails" Text="+"
                       CommandName="Show" Font-Name="Verdana" />
                   <b>
                       <%# DataBinder.Eval(Container.DataItem, "Id") %>
                   </b>
                   <br />
                   <asp:Label ID="lblEID" Visible="False" runat="Server" Text='<%# DataBinder.Eval(Container.DataItem, "ID") %>' />
                   <asp:DataGrid runat="server" ID="Datagrid1" Font-Name="Verdana" Font-Size="10pt"
                       HorizontalAlign="Center" Visible="False" Width="85%"/>
               </ItemTemplate>
           </asp:DataList>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataListHide : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            Datalist1.DataSource = CreateDS();
            Datalist1.DataBind();
        }

    }
    private DataSet CreateDS()
    {
        DataSet ds;
        if (Session["DataList_ParentChild"] == null)
        {
            ds = new DataSet();
            DataTable dt = new DataTable("Company");
            DataRow dr;
            dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
            dt.Columns.Add(new DataColumn("CompanyName", typeof(string)));
            dt.Columns.Add(new DataColumn("Address", typeof(string)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Dept", typeof(string)));
            for (int i = 1; i < 10; i++)
            {
                dr = dt.NewRow();
                dr[0] = i;
                dr[1] = "Company " + i;
                dr[2] = "Address " + i;
                dr[3] = "Manager name";
                dr[4] = "Adminstration";
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);
            DataColumn[] Parent_PKColumns = new DataColumn[1];
            Parent_PKColumns[0] = dt.Columns["ID"];
            dt.PrimaryKey = Parent_PKColumns;

            dt = new DataTable("Employees");
            dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
            dt.Columns.Add(new DataColumn("CompanyID", typeof(Int32)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Dept", typeof(string)));
            for (int i = 1; i < 10; i++)
            {
                int imax = 0;
                if (i % 2 == 0) imax = 5;
                else imax = 4;
                for (int y = 2; y < imax; y++)    //3 emplyees for each company
                {
                    dr = dt.NewRow();
                    dr[0] = y + i * 5;
                    dr[1] = i;
                    dr[2] = "Employee # " + dr[0];
                    dr[3] = "Dept # " + (y + i);
                    dt.Rows.Add(dr);
                }
            }
            DataColumn[] Child_PKColumns = new DataColumn[1];
            Child_PKColumns[0] = dt.Columns["ID"];
            dt.PrimaryKey = Child_PKColumns;
            ds.Tables.Add(dt);
            DataColumn[] Child_FKColumns = new DataColumn[1];
            Child_FKColumns[0] = dt.Columns["CompanyID"];




            ds.Relations.Add("ParentChild", Parent_PKColumns, Child_FKColumns);
            Session["DataList_ParentChild"] = ds;
        }
        else
        {
            ds = (DataSet)Session["DataList_ParentChild"];
        }
        return ds;

    }
    protected void Datalist1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "Show")
        {
            Label EmpIDlabel = (Label)e.Item.FindControl("lblEID");
            string strEmpID = EmpIDlabel.Text;
            ((DataGrid)e.Item.FindControl("Datagrid1")).DataSource = GetEmpDetails(strEmpID);
            ((DataGrid)e.Item.FindControl("Datagrid1")).DataBind();
            ((DataGrid)e.Item.FindControl("Datagrid1")).Visible = true;
            ((LinkButton)e.Item.FindControl("btnDetails")).Text = "-";
            ((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Hide";
        }
        if (e.CommandName == "Hide")
        {
            ((DataGrid)e.Item.FindControl("Datagrid1")).Visible = false;
            ((LinkButton)e.Item.FindControl("btnDetails")).Text = "+";
            ((LinkButton)e.Item.FindControl("btnDetails")).CommandName = "Show";
        }
    }
    protected DataView GetEmpDetails(string id)
    {

        DataSet ds = CreateDS() as DataSet;
        DataView dv = ds.Tables[1].DefaultView;
        dv.RowFilter = "CompanyID=" + id;
        return dv;

    }


}

How To change the background image of html table placed in gridview's template field.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicDiv2.aspx.cs" Inherits="DynamicDiv2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="Server" OnRowDataBound="GridView1_RowDataBound1">
              <Columns>
                  <asp:TemplateField>
                      <ItemTemplate>
                          <table id="myTable" runat="server" width="200px" height="150px">
                              <tr>
                                  <td>
                                      <asp:Label ID="lblName" runat="Server" Text='<%#Eval("Name")%>'></asp:Label>
                                  </td>
                              </tr>
                          </table>
                      </ItemTemplate>
                  </asp:TemplateField>
              </Columns>
          </asp:GridView>
      </div>
  </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class DynamicDiv2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       if (!IsPostBack)
       {
           List<dataStruct> mylist = new List<dataStruct>();

           mylist.Add(new dataStruct(new DateTime(1982, 01, 01), "Bill", 'm'));
           mylist.Add(new dataStruct(new DateTime(1981, 01, 01), "Philip", 'm'));
           mylist.Add(new dataStruct(new DateTime(1980, 01, 01), "Susan", 'f'));

           GridView1.DataSource = mylist;
           GridView1.DataBind();
       }

   }

   public struct dataStruct
   {

       private DateTime birthdate;
       private string name;
       private char sex;
       public DateTime BirthDate
       {
           get { return birthdate; }
           set { birthdate = value; }
       }

       public string Name
       {
           get { return name; }
           set { name = value; }
       }

       public char Sex
       {
           get { return sex; }
           set { sex = value; }
       }


       public dataStruct(DateTime _birthdate, string _name, char _sex)
       {

           this.birthdate = _birthdate;
           this.name = _name;
           this.sex = _sex;
       }
   }

   protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           HtmlTable tbl = (HtmlTable)e.Row.FindControl("myTable");
           if (tbl != null)
           {
               if (((Label)tbl.FindControl("lblName")).Text == "Bill")
               {
                   tbl.Attributes.Add("style", "color:red;background-color:green;height:50px);");
               }
               else if (((Label)tbl.FindControl("lblName")).Text == "Philip")
               {
                   tbl.Attributes.Add("style", "background-image:url(images/pdf-icon.jpg);");
               }
               else
               {
                   tbl.Attributes.Add("style", "background-image:url(images/mime_text.png);");
               }

           }
       }

   }
}

Wednesday, August 27, 2008

Adding/Using Embedded Resources in .Net Web Application/Class Library (C#/VB.Net/ASP.Net)

In .Net when you don’t want to relay for a file on physical location, then it is very good option to take an advantage of Embedded resources. Using embedded resources you can add any file type in the assembly/DLL/EXE when they get compiled. And whenever you want to use it, load it from the assembly, the files get stored in the metadata of Assembly. Here is an example of how to use Embedded Resources. 1. Open Microsoft Visual Studio and create new project for C# Windows Application, here I have created Windows Application named “EmbeddedTest”, even you can use “Class Library” 2. To add a file in the project Right click on the project name in Solution Explorer, select “Add” >> “Existing Item…” 3. Now we have added a file to the project, so it doesn’t mean that it will automatically embedded in the Assembly, for that we need to change the files “Build Action” property to “Embedded Resource”, and compiler will include this file in metatdata. Here I have added Image file(blue.jpg), you can add one or more any kind of files Now use the following code in Form1_Load method to list all the Embedded Resources available in the Assembly
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] resources = ImageLibrary.Images.GetNames();

        foreach (string resourceName in resources)
        {
            ListBox1.Items.Add(resourceName);
        }
    }
}
5. The following code is used to get the resource from the Manifest of the Assembly when user clicks on the listBox1
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (ListBox1.SelectedIndex == -1)
         return;

     string selectedResourceName = ListBox1.SelectedItem.ToString();

    System.Drawing.Image  img = ImageLibrary.Images.GetImageByResourceName(selectedResourceName);
     if (img != null)
     {
         System.Drawing.Bitmap obj = new System.Drawing.Bitmap(img);
         Response.ContentType = "image/gif";


         obj.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
    
     }
     else
     {
    
    
     }
 

 }
complete code
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Reflection;

using System.IO;

namespace ImageLibrary
{
  public class Images
  {
      public static string[] GetNames()
      {
          Assembly a = Assembly.GetExecutingAssembly();

          return a.GetManifestResourceNames();
      }

      public static Image GetImageByResourceName(string resourceName)
      {
          Assembly a = Assembly.GetExecutingAssembly();

          try
          {
              Stream stream = a.GetManifestResourceStream(resourceName);

              return Bitmap.FromStream(stream) as Bitmap;
          }
          catch (Exception ex)
          {
              return null;
          }
      }
  }
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmbeedTest.aspx.cs" Inherits="EmbeedTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Untitled Page</title>
</head>
<body>
  <form id="form1" runat="server">
      <div>
          <table style="width: 100%">
              <tr>
                  <td style="width: 100px">
                      <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
                      </asp:ListBox></td>
                  <td style="width: 100px">
                  </td>
              </tr>
          </table>
      </div>
  </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class EmbeedTest : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
      if (!IsPostBack)
      {
          string[] resources = ImageLibrary.Images.GetNames();

          foreach (string resourceName in resources)
          {
              ListBox1.Items.Add(resourceName);
          }
      }
  }
  protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
      if (ListBox1.SelectedIndex == -1)
          return;

      string selectedResourceName = ListBox1.SelectedItem.ToString();

     System.Drawing.Image  img = ImageLibrary.Images.GetImageByResourceName(selectedResourceName);
      if (img != null)
      {
          System.Drawing.Bitmap obj = new System.Drawing.Bitmap(img);
          Response.ContentType = "image/gif";


          obj.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
      
      }
      else
      {
      
      
      }
   

  }
}

How To Use Out Parameter

<%@ Page Language="C#" %>
<script runat="server">

    void Page_Load()
    {
        int a = 1;
        int b;
        Increment(a, out b);
        lblMessage.Text = b.ToString();
    }
   
    void Increment(int Number, out int Result)
    {
        Result = Number + 1;
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demonstration of using out Parameters</title>
</head>
<body>
    <form id="form1" runat="server">

    <asp:Label id="lblMessage" runat="server"></asp:Label>


</form>
</body>
</html>

Working with postback of dropdown list inside Gridview

Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list. We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.

A simple solution to the problem is to use the namingcontainer in the selectedindexchanged event and get the reference of the parent row view. After that we can do what we want from the row view. Here is an example in the code.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewDropDown.aspx.cs"
   Inherits="GridViewDropDown" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
               <Columns>
                   <asp:TemplateField HeaderText="Publisher">
                       <ItemTemplate>
                           <asp:DropDownList ID="ddlPub" runat="Server" AutoPostBack="true" OnSelectedIndexChanged="ddlPub_SelectedIndexChanged"
                               DataSource='<%#GetCustomMadeDataTable()%>' DataTextField="Publisher">
                           </asp:DropDownList>
                       </ItemTemplate>
                   </asp:TemplateField>
                   <asp:TemplateField HeaderText="Title">
                       <ItemTemplate>
                           <asp:DropDownList ID="ddlTitle" runat="Server">
                           </asp:DropDownList>
                       </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GridViewDropDown : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridViewView();
            this.DataBind();
        }
    }
    private void BindGridViewView()
    {
        if (Session["strTemp"] != null)
        {

            GridView1.DataSource = Session["strTemp"] as DataTable;
            GridView1.DataBind();

        }
        else
        {
            GridView1.DataSource = GetCustomMadeDataTable();
            GridView1.DataBind();
        }
    }


    public DataTable GetCustomMadeDataTable()
    {
        //Create a new DataTable object
        System.Data.DataTable objDataTable = new System.Data.DataTable();
        //Create three columns with string as their type
        objDataTable.Columns.Add("ISBN", typeof(int));
        objDataTable.Columns.Add("Title", typeof(string));
        objDataTable.Columns.Add("Publisher", typeof(string));
        objDataTable.Columns.Add("Year", typeof(string));
        DataColumn[] dcPk = new DataColumn[1];
        dcPk[0] = objDataTable.Columns["ISBN"];
        objDataTable.PrimaryKey = dcPk;
        objDataTable.Columns["ISBN"].AutoIncrement = true;
        objDataTable.Columns["ISBN"].AutoIncrementSeed = 1;
        //Adding some data in the rows of this DataTable
        DataRow dr;
        for (int i = 1; i <= 5; i++)
        {
            dr = objDataTable.NewRow();
            dr[1] = "Title" + i.ToString();
            dr[2] = "Publisher" + i.ToString();
            dr[3] = "200" + i.ToString();
            objDataTable.Rows.Add(dr);
        }
        for (int i = 6; i <= 8; i++)
        {
            dr = objDataTable.NewRow();
            dr[1] = "Computer" + i.ToString();
            dr[2] = "TMH" + i.ToString();
            dr[3] = "200" + i.ToString();
            objDataTable.Rows.Add(dr);
        }
        Session["strTemp"] = objDataTable;
        return objDataTable;
    }

    protected ArrayList RelatedData(string s)
    {
        ArrayList ar = new ArrayList();
        if (s == "Publisher1")
        {

            ar.Add("Book1");
            ar.Add("Book2");


        }
        if (s == "Publisher2")
        {

            ar.Add("Computer");
            ar.Add("C#");

        }
        return ar;
    }
    protected void ddlPub_SelectedIndexChanged(object sender, EventArgs e)
    {
        // get reference to the row
        GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);

        // Get the reference of this DropDownlist
        DropDownList dropdownlist1 = (DropDownList)gvr.FindControl("ddlPub");

        // Get the reference of other DropDownlist in the same row.
        DropDownList ddlParagraph = (DropDownList)gvr.FindControl("ddlTitle");

        string strValue = dropdownlist1.SelectedItem.Text;
        ddlParagraph.DataSource = RelatedData(strValue);
        ddlParagraph.DataBind();
    }
}

Tuesday, August 26, 2008

How To Create your Own Custom Events

In this post i will show how to extend EventArgs class. 1) Create your custom event args class derived from System.EventArgs 2) Declare your delegate with two parameters, object source and YourEventArgsClass e. 3) Create a protected virtual method that fires the event for you (its protected and virtual so that deriving class can see the method and also override it if they wish to change how and when the event is fired)

using System;

public class MyEventArgs : System.EventArgs
{
   private bool m_OldValue;
   private bool m_NewValue;

   public MyEventArgs(bool oldVal, bool newVal)
   {
       this.m_OldValue = oldVal;
       this.m_NewValue = newVal;
   }

   public bool OldValue
   {
       get { return this.m_OldValue; }
   }

   public bool NewValue
   {
       get { return this.m_NewValue; }
   }
}
public class MyClass
{
   public delegate void ValueChangedHandler(object source, MyEventArgs e);
   public event ValueChangedHandler ValueChanged;

   private bool m_MyBool = false;

   public MyClass() { }

   public void SomeMethod()
   {
       this.MyBool = true;
   }

   public bool MyBool
   {
       get { return this.m_MyBool; }
       set
       {
           //Now call our virtual method, with the old and new value (this fires the event for us)
           this.OnValueChanged(new MyEventArgs(this.m_MyBool, value));
           this.m_MyBool = value;
       }
   }

   protected virtual void OnValueChanged(MyEventArgs e)
   {
       this.ValueChanged(this, e);
   }
}

class Test
{


   public static void Main()
   {

       MyClass obj = new MyClass();
       obj.ValueChanged += new MyClass.ValueChangedHandler(obj_ValueChanged);
       obj.SomeMethod();
       Console.Read();

   }

   static void obj_ValueChanged(object source, MyEventArgs e)
   {
       if (e.NewValue == false)
       {
           Console.WriteLine("Hi");
           Console.Read();
       }
       else
       {
           Console.WriteLine("bye");
           Console.Read();
       }
   }

}

UserControl and Event

I will create a new and very simple UserControl, to illustrate how to create events. It won't have a real life purpose, but is only meant to show you how to use events in a UserControl. First, we create a new, simple EventUserControl, with this code in it:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.ascx.cs"
Inherits="EventUserControl" %>
Page title:
<asp:TextBox runat="server" ID="txtPageTitle" />
<asp:Button runat="server" ID="btnUpdatePageTitle" OnClick="btnUpdatePageTitle_Click"
Text="Update" />
All just text and server controls that we know. In the CodeBehind, it looks a bit like this:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class EventUserControl : System.Web.UI.UserControl
{
 private string pageTitle;
 public event EventHandler PageTitleUpdated;

 protected void btnUpdatePageTitle_Click(object sender, EventArgs e)
 {
     this.pageTitle = txtPageTitle.Text;
     if (PageTitleUpdated != null)
         PageTitleUpdated(this, EventArgs.Empty);
 }

 public string PageTitle
 {
     get { return pageTitle; }
 }
}

We have defined a pageTitle container variable and a property for it. Then we have a new thing, an event. As you can see, it's defined much like any other kind of field, but it is a bit different. The theory about is explained in the C# tutorial, so we won't get into that here. In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated, our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we send this (a reference to the UserControl it self) as the sender, and an empty EventArgs parameter. This will make sure that all subscribers are notified that the pageTitle has just been updated. Now, in our page, I've declared our UserControl like this:
<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EventUserControl.aspx.cs"
   Inherits="EventUserControl" %>

<%@ Register TagPrefix="My" TagName="EventUserControl" Src="~/EventUserControl.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <My:EventUserControl runat="server" ID="MyEventUserControl" OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class EventUserControl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e)
    {
        this.Title = MyEventUserControl.PageTitle;
    }

}