Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi I need some advice/help with my expandable Gridview. I am trying to map the contents of "c:\inetpub" to a gridview. I have been debugging my code and can see rows being added to my DataTable gvSource but whenever I bind this DT to the Gridview I get the following error:
"Object reference not set to an instance of an object. at gvFiles_RowDataBound(Object sender, GridViewRowEventArgs e)" in particular this line:
C#
var item = e.Row.DataItem as FileSystemItemCS;
item is being set to null

I'll include my code so far:
front end Control code
ASP.NET
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="BrowseFilesUsrCtrl.ascx.cs" Inherits="SrvViewingTool.Controls.BrowseFilesUsrCtrl" %>

<table width="100%">
    <tr>
        <td style="width: 631px; removed: static; removed 10px; height: 16px" valign="top">
            <asp:Label ID="lblDateMod" runat="server" EnableViewState="False" Font-Bold="False" Font-Names="Arial Narrow"
                Font-Size="Smaller"></asp:Label></td>
        <td style="width: 1604px; removed: static; height: 16px" valign="top" colspan="2">
            <asp:Label ID="lblFile" runat="server" Font-Bold="False" Font-Names="Arial Narrow" Font-Size="Smaller" EnableViewState="False"></asp:Label></td>
    </tr>
    <tr>
        <td style="width: 371px; removed: static; removed 10px; height: 232px" valign="top" >
           <asp:UpdatePanel ID="Panel1" runat="server">
           <ContentTemplate>
                <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="False" 
                    CellPadding="4" ForeColor="#333333" GridLines="None" 
                    onpageindexchanging="gvFiles_PageIndexChanging" 
                    onrowcommand="gvFiles_RowCommand" onrowdatabound="gvFiles_RowDataBound" 
                     Width="370px">
                    <AlternatingRowStyle BackColor="White" Width="700px" Font-Size="Small" />
                    <Columns>
                        <asp:BoundField DataField="FullPath" HeaderText="FileName" SortExpression="FullPath">
                        </asp:BoundField>
                        <asp:TemplateField HeaderText="Name" SortExpression="FullPath">
                            <ItemTemplate>
                                <asp:LinkButton runat="server" ID="lbFolderItem" Text='<%#Eval("FullPath")%>'  
                                CommandName="OpenFolder" CommandArgument='<%# Eval("FullPath") %>' >
                                </asp:LinkButton>
                                <asp:Literal runat="server" ID="ltlFileItem"></asp:Literal>                         
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Extention" HeaderText="Ext" SortExpression="Extention">
                        </asp:BoundField>
                        <asp:BoundField DataField="Size" DataFormatString="{0:N0}" HeaderText="Size" HtmlEncode="False"
                            SortExpression="Size">
                            <ItemStyle HorizontalAlign="Right" Wrap="False" />
                        </asp:BoundField>
                        <asp:BoundField DataField="LastWriteTime" DataFormatString="{0:d}" HeaderText="Date Modified"
                            HtmlEncode="False" SortExpression="LastWriteTime">
                            <ItemStyle HorizontalAlign="Right" Wrap="False" />
                        </asp:BoundField>
                    </Columns>
                    <EditRowStyle BackColor="#2461BF" />
                    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#EFF3FB" />
                    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />    
                </asp:GridView>
           </ContentTemplate>
           </asp:UpdatePanel>
        </td>
        <td style="width: 100%; removed: static; height: 100%" valign="top">
            <asp:TextBox ID="tbxContents" runat="server" Font-Names="Courier New" Font-Size="Small"
            Height="508px" ReadOnly="True" TextMode="MultiLine" Visible="True" Width="99%"
            Wrap="False" EnableViewState="False"></asp:TextBox>
        </td>
    </tr>
</table>
<asp:HiddenField ID="HiddenField1" runat="server" />



CodeBehind Control
C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                ShowEdit(false);        
        }

        void Page_PreRender(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if(DirPath!="None")
                    PopulateGrid();   
            }
        }

        public override void DataBind()
        {
            if (DirPath != "None")
                PopulateGrid();
        }

        protected void PopulateGrid()
        {
            try
            {
                DataTable gvSource = DisplayFilesInGridView();
                DataRow gvRow;

                //Get All Folders Or Directories and add in table
                DirectoryInfo directory = new DirectoryInfo(@DirPath);//(@"c:\inetpub");
                DirectoryInfo[] subDirectories = directory.GetDirectories();
                foreach (DirectoryInfo dirInfo in subDirectories)
                {
                    gvRow = gvSource.NewRow();
                    gvRow["FullPath"] = dirInfo.Name;
                    gvRow["Extention"] = "Directory";
                    gvRow["Size"] = 0;
                    gvRow["LastWriteTime"] = dirInfo.LastWriteTime;
                    gvRow["IsFolder"] = 1;
                    gvRow["ImageUrl"] = @"~\Images\Folder.gif";
                    gvSource.Rows.Add(gvRow);                    
                }

                //Get files in all directories 
                FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
                foreach (FileInfo fileInfo in files)
                {
                    bool canView = false;
                    try
                    {
                        string ext = ConfigurationManager.AppSettings["ViewExt"];
                        string[] extensions = ext.Split(';');
                        foreach (string extension in extensions)
                        {
                            if (String.Compare(fileInfo.Extension, extension, true) == 0)
                            {
                                canView = true;
                                break;
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }

                    if (canView)
                    {
                        gvRow = gvSource.NewRow();
                        gvRow["FullPath"] = fileInfo.Name;
                        gvRow["Size"] = fileInfo.Length;
                        gvRow["Extention"] = "File";
                        gvRow["LastWriteTime"] = fileInfo.LastWriteTime;
                        gvRow["IsFolder"] = 0;
                        //could do a switch to get correct image for each file type
                        switch (fileInfo.Extension)
                        {
                            case ".txt":
                            case ".log":
                                gvRow["ImageUrl"] = @"~\Images\page.gif";
                                break;
                            case ".bat":
                                gvRow["ImageUrl"] = @"~\Images\BAT.ico";
                                break;
                            case ".ini":
                                gvRow["ImageUrl"] = @"~\Images\INI.ico";
                                break;
                            case ".config":
                                gvRow["ImageUrl"] = @"~\Images\XML.ico";
                                break;
                            case ".aspx":
                                gvRow["ImageUrl"] = @"~\Images\ASPX.gif";
                                break;
                            case ".xml":
                                gvRow["ImageUrl"] = @"~\Images\XML.ico";
                                break;
                            default:
                                gvRow["ImageUrl"] = @"~\Images\page.gif";
                                break;
                        }
                        //gvRow["ImageUrl"] = @"~\Images\Windows.gif";
                        gvSource.Rows.Add(gvRow);
                    }
                    else if (String.Compare(fileInfo.Extension, ".exe", true) == 0 ||
                            String.Compare(fileInfo.Extension, ".dll", true) == 0)
                    {
                        //tbxContents.Text = String.Format("Version:\t{0}\nDateModified:\t{1}\nSize(bytes):\t{2}",
                        //    System.Diagnostics.FileVersionInfo.GetVersionInfo(node.Value).ProductVersion,
                        //    dt.ToLocalTime().ToString(), fi.Length);
                        //lblFile.Text = node.Value + "  [Date Modified: " + dt.ToLocalTime().ToString() + "]";
                        ShowEdit(true);
                    }
                    else
                    {
                        lblDateMod.Text = "Current File/Dir Last Modified on: " + fileInfo.LastWriteTimeUtc.ToString();
                        ShowEdit(false);
                    }
                }


                gvFiles.DataSource = gvSource;
                gvFiles.DataBind();
            }
            catch (Exception ex)
            {
                tbxContents.Text = ex.Message;
            }
        }

        private DataTable DisplayFilesInGridView()
        {
            DataTable dtGvSource = new DataTable();
            dtGvSource.Columns.Add("FullPath", typeof(String));
            dtGvSource.Columns.Add("Extention", typeof(String));
            dtGvSource.Columns.Add("size", typeof(Int32));
            dtGvSource.Columns.Add("LastWriteTime", typeof(DateTime));
            dtGvSource.Columns.Add("IsFolder", typeof(Boolean));
            dtGvSource.Columns.Add("ImageUrl", typeof(String));            
            return dtGvSource;
        }

protected void gvFiles_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvFiles.PageIndex = e.NewPageIndex;

            PopulateGrid();
        }

        protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenFolder")
            {
                if (string.CompareOrdinal(e.CommandArgument.ToString(), "..") == 0)
                {
                    var currentFullPath = this.CurrentFolder;
                    if (currentFullPath.EndsWith("\\") || currentFullPath.EndsWith("/"))
                        currentFullPath = currentFullPath.Substring(0, currentFullPath.Length - 1);

                    currentFullPath = currentFullPath.Replace("/", "\\");

                    var folders = currentFullPath.Split("\\".ToCharArray());

                    this.CurrentFolder = string.Join("\\", folders, 0, folders.Length - 1);
                }
                else
                    this.CurrentFolder = Path.Combine(this.CurrentFolder, e.CommandArgument as string);


                PopulateGrid();
            }
        }

        protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var item = e.Row.DataItem as FileSystemItemCS;

                if (item.IsFolder)
                {
                    var lbFolderItem = e.Row.FindControl("lbFolderItem") as LinkButton;
                    lbFolderItem.Text = string.Format(@"<img src=""{0}"" alt="""" /> {1}", Page.ResolveClientUrl("~/Images/folder.png"), item.Name);
                }
                else
                {
                    var ltlFileItem = e.Row.FindControl("ltlFileItem") as Literal;
                    if (this.CurrentFolder.StartsWith("~"))
                        ltlFileItem.Text = string.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                                Page.ResolveClientUrl(string.Concat(this.CurrentFolder, "/", item.Name).Replace("//", "/")),
                                item.Name);
                    else
                        ltlFileItem.Text = item.Name;
                }
            }
        }


FileSystemItemCS.cs
C#
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SrvViewingTool
{
    public class FileSystemItemCS
    {
        public FileSystemItemCS(FileInfo file)
        {
            this.Name = file.Name;
            this.FullName = file.FullName;
            this.Size = file.Length;
            this.CreationTime = file.CreationTime;
            this.LastAccessTime = file.LastAccessTime;
            this.LastWriteTime = file.LastWriteTime;
            this.IsFolder = false;
        }

        public FileSystemItemCS(DirectoryInfo folder)
        {
            this.Name = folder.Name;
            this.FullName = folder.FullName;
            this.Size = null;
            this.CreationTime = folder.CreationTime;
            this.LastAccessTime = folder.LastAccessTime;
            this.LastWriteTime = folder.LastWriteTime;
            this.IsFolder = true;
        }

        public string Name { get; set; }
        public string FullName { get; set; }
        public long? Size { get; set; }
        public DateTime CreationTime { get; set; }
        public DateTime LastAccessTime { get; set; }
        public DateTime LastWriteTime { get; set; }
        public bool IsFolder { get; set; }

        public string FileSystemType
        {
            get
            {
                if (this.IsFolder)
                    return "File folder";
                else
                {
                    var extension = Path.GetExtension(this.Name);

                    if (IsMatch(extension, ".txt"))
                        return "Text file";
                    else if (IsMatch(extension, ".pdf"))
                        return "PDF file";
                    else if (IsMatch(extension, ".doc", ".docx"))
                        return "Microsoft Word document";
                    else if (IsMatch(extension, ".xls", ".xlsx"))
                        return "Microsoft Excel document";
                    else if (IsMatch(extension, ".jpg", ".jpeg"))
                        return "JPEG image file";
                    else if (IsMatch(extension, ".gif"))
                        return "GIF image file";
                    else if (IsMatch(extension, ".png"))
                        return "PNG image file";


                    // If we reach here, return the name of the extension
                    if (string.IsNullOrEmpty(extension))
                        return "Unknown file type";
                    else
                        return extension.Substring(1).ToUpper() + " file";
                }
            }
        }

        private bool IsMatch(string extension, params string[] extensionsToCheck)
        {
            foreach (var str in extensionsToCheck)
                if (string.CompareOrdinal(extension, str) == 0)
                    return true;

            // If we reach here, no match
            return false;
        }
    }
}
Posted
Comments
Yuriy Loginov 10-May-13 8:59am    
instead of casting to FileSystemItemCS try creating an instance, something like the code below. You will need to add another constructor to FileSystemItemCS.
I think that error comes because it cant convert row type to your type which leaves var item null

FileSystemItemCS item = new FileSystemItemCS(e.Row.DataItem["size"].........)
pmcm 10-May-13 9:34am    
What additional constructor is required to FileSystemItemCS?
Yuriy Loginov 10-May-13 9:40am    
try adding the one that matches the definition of your DataItem

public FileSystemItemCS(string FullPath, string extension, long size, DateTime LastWriteTime, bool IsFolder, string ImafeUrl)....
pmcm 10-May-13 9:40am    
Also tried adding FileSystemItemCS item = new FileSystemItemCS(e.Row.DataItem["size"]). A folder or file is expected here new FileSystemItemCS(Directory/File)

and now getting this error: "Cannot apply indexing with [] to an expression of type 'object'"

Thanks
Yuriy Loginov 10-May-13 9:43am    
try doing e.Row["property_name"] instead

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900