Multiple Attachment Custom Control in Sharepoint

Hey guys, sorry for not writing this part within the same period I've written the previous 3 parts, but that is because I wanted to be sure that the code is written without bugs, so in the previous 3 weeks we have tested the control extensively and solved many issues we have found in it and now its stable, so finally we have decided to post the code to continue our 4 part series of articles.

We will now explain the most important part of our Multiple upload attachment control implementation, which is the class that implements all the logic of our control.

Remember: The control we are going to make is a control that adds multiple attachments to each of 3 lists regarding the type of the file you are going to upload. The three types of files we have are Images, Videos and other files or PDF.

So after uploading any file there is a GUID id generated as an id for the file that is saved with the same list as a name for the file uploaded and as a title for the file, the title column will contain the file name and the GUIDs of all the items that contains this file.

I know that this article may be somehow unclear but I think some photos will make everything more obvious.

In the next image is the back-end of our control, this is how to create a new column of the type of our Uploader.

Here you will specify the 3 lists to be uploaded of your files, these lists are preferred to be on the root of your application and then you will specify the number of files you want to upload per each type, if you want to disable uploading images for example then just make the number of image files = 0 and by that you can put Images list name = any string as null.

image1.gif

And this image is the layout of our control.

image2.gif

image3.gif

And that is how to select a file from the previous files you've uploaded and the existing files are loaded from the list related to the type you are choosing.

Uploading files.

image4.gif

The following picture shows the item added in the images list and as shown it's name is a GUID representing this file id and its title is: Testing File.Jpg * (the GUID id of the main item that contains this file).

image5.gif


And after creating the main item in my list that will contain many attached files it will be shown as follows:

image6.gif

In the previous image you can see the item with title = News Item and the value stored in the Multiple File Uploader is the GUID id representing this item and this id is used to connect the item with its related uploaded files as shown in the picture of the images list (the id of the news item is the same as found in the title column of the image created in the images list) .


I think by now everything is more clear so I can post the code that implements this control.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Threading;
using System.Web.UI;
using System.Data;
using System.Web.UI.HtmlControls;

namespace SpCustomFields
{
    public class FileUploader : SPFieldText
    {
        public static string internalFieldName = string.Empty;
        public static bool isRequired = false;

        public FileUploader(SPFieldCollection spFieldCollection, string spName)
            : base(spFieldCollection, spName)
        { }

        public FileUploader(SPFieldCollection spFieldCollection, string spName, string dispName)
            : base(spFieldCollection, spName, dispName)
        { }
 
        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                isRequired = this.Required;
                internalFieldName = this.InternalName;
                FileUploaderImplementation fileControl = new FileUploaderImplementation();
                fileControl.FieldName = this.InternalName;
                return fileControl;
 
            }
        }
 
        public override object GetFieldValue(string value)
        {
            return base.GetFieldValue(value);
        }
    }

    public class FileUploaderImplementation : BaseFieldContro
    {

        #region Form Controls and Variable initialization

        FileUpload fileUploader;
        LinkButton btnUpload;
        TextBox FileNameTextBox;
        RadioButton RdImages, RdPdfs, RdVideos, RdUpload, RdSelect;
        GridView UploadingGrid;
        DropDownList SelectDropDown;
        CustomValidator customUploadValidator;
        RequiredFieldValidator UploadRequiredValidator, FileNameRequiredValidator, GridValidator;
        Label lblFileName;
        TextBox HiddenFieldGridValidator;

        string ImagesUploadList, VideosUploadList, PdfsUploadList;
        int ImagesMaximumLength, VideosMaximumLength, PdfsMaximumLength;
        bool extFound = false;
        public static string newsItemId = string.Empty;
 
        #endregion

        #region Main Functions to be overrided for the custom control

        protected override string DefaultTemplateName
        {
            get
            {
                return "FileUploaderTemplate";
            }
        }

        public override void Focus()
        {
            EnsureChildControls();
            fileUploader.Focus();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
 
            //Reading lists names.
            try
            {
                ImagesUploadList = this.Field.GetCustomProperty("ImagesList").ToString();
                VideosUploadList = this.Field.GetCustomProperty("VideosList").ToString();
                PdfsUploadList = this.Field.GetCustomProperty("PdfsList").ToString();

                ImagesMaximumLength = int.Parse(this.Field.GetCustomProperty("ImagesMaximumLength").ToString());
                VideosMaximumLength = int.Parse(this.Field.GetCustomProperty("VideosMaximumLength").ToString());
                PdfsMaximumLength = int.Parse(this.Field.GetCustomProperty("PdfsMaximumLength").ToString());

            }
            catch
            {
                //To do: Log Exception.
            }

            if (ControlMode == SPControlMode.New || ControlMode == SPControlMode.Edit)
            {

                #region rendering all controls
                try
                {
                    lblFileName = (Label)TemplateContainer.FindControl("lblFileName");
                    FileNameTextBox = (TextBox)TemplateContainer.FindControl("FileNameTextBox");

                    RdImages = (RadioButton)TemplateContainer.FindControl("RdImages");
                    RdPdfs = (RadioButton)TemplateContainer.FindControl("RdPdfs");
                    RdVideos = (RadioButton)TemplateContainer.FindControl("RdVideos");
                    RdUpload = (RadioButton)TemplateContainer.FindControl("RdUpload");
                    RdSelect = (RadioButton)TemplateContainer.FindControl("RdSelect");

                    customUploadValidator =
                    (CustomValidator)TemplateContainer.FindControl("UploadControlCustomValidator");

                    UploadRequiredValidator = (RequiredFieldValidator)TemplateContainer.FindControl("UploadControlRequiredValidator");
                    FileNameRequiredValidator = (RequiredFieldValidator)TemplateContainer.FindContr("FileNameRequiredValidator");
                    GridValidator = (RequiredFieldValidator)TemplateContainer.FindControl("GridValidator");
 
                    fileUploader = (FileUpload)TemplateContainer.FindControl("FilesUploader");
                    SelectDropDown = (DropDownList)TemplateContainer.FindControl("SelectDropDown");
                    btnUpload = (LinkButton)TemplateContainer.FindControl("UploadButton");
                    UploadingGrid = (GridView)TemplateContainer.FindControl("UploadingGrid");
                    HiddenFieldGridValidator = (TextBox)TemplateContainer.FindControl("HiddenFieldGridValidator");

                }
                catch
                {
                    //To do: Log the Exception
                }
                #endregion

                #region defining controls properties and assigning events to them
                try
                {
                    btnUpload.Click += new EventHandler(BtnUploadClick);
                    RdUpload.CheckedChanged += new EventHandler(UploadOrSelect);
                    RdSelect.CheckedChanged += new EventHandler(UploadOrSelect);
                    RdPdfs.CheckedChanged += new EventHandler(FillInSelectDropDown);
                    RdVideos.CheckedChanged += new EventHandler(FillInSelectDropDown);
                    RdImages.CheckedChanged += new EventHandler(FillInSelectDropDown);

                    customUploadValidator.ServerValidate += new ServerValidateEventHandler(customUploadValidator_ServerValidate);
                    UploadingGrid.RowDeleting += new GridViewDeleteEventHandler(UploadingGridRowDelete);
                    DataTable dt = new DataTable();

                    if (ViewState["UploadingGrid"] != null)
                    {
                        dt = (DataTable)ViewState["UploadingGrid"];
                    }
                    UploadingGrid.DataSource = dt;
                    UploadingGrid.DataBind();
 
                }
 
                catch
                {
                    // To do: Log the Exception
                }
 
                #endregion

                CheckDataGrid();
                newsItemId = UpdateNewsItemID();
                CheckUploadStatus();
            }
            if (ControlMode == SPControlMode.Edit)
            {
                HiddenFieldGridValidator.Text = "Edit mode";
                FileNameRequiredValidator.Visible = false;
                UploadRequiredValidator.Visible = false;
                FillInGridWithUploads();
                newsItemId = UpdateNewsItemID();
                CheckUploadStatus();
            }

        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                return newsItemId;
            }
            set
            {
                EnsureChildControls();
                base.Value = newsItemId;
            }
        }
 
        #endregion

        #region Form Events

        void BtnUploadClick(object sender, EventArgs e)
        {
            FileNameRequiredValidator.Visible = true;
            UploadRequiredValidator.Visible = true;
            FileNameRequiredValidator.Validate();
            UploadRequiredValidator.Validate();

            if (string.IsNullOrEmpty(newsItemId) && ControlMode == SPControlMode.New)
            {
                newsItemId = Guid.NewGuid().ToString();
            }
            else if (ControlMode == SPControlMode.Edit && this.Value != null && string.IsNullOrEmpty(this.Value.ToString()))
            {
                newsItemId = UpdateNewsItemID();
            }
            else
            {
                newsItemId = UpdateNewsItemID();
            }
            if (SelectDropDown.Visible == true || extFound)
            {
                if (fileUploader.Visible == true && fileUploader.HasFile && fileUploader.FileBytes != null && FileNameRequiredValidator.IsValid && UploadRequiredValidator.IsValid)
                {
                    AddUploadsToUploadingGrid();
                    AddUploadsToDocLib();
                    CheckUploadStatus();
                    FileNameTextBox.Text = string.Empty;

                }
                else if (SelectDropDown.Visible == true)
                {
                    AddUploadsToUploadingGrid();
                    AddSelectedToNewsItem();
                    CheckUploadStatus();
                }
 
            }
        }

        private void FillInSelectDropDown(object sender, EventArgs e)
        {
            if (RdSelect.Checked && sender != null)
            {
                string lstName = string.Empty;

                if (((RadioButton)sender).ID == "RdImages")
                {
                    lstName = ImagesUploadList;
                }
                if (((RadioButton)sender).ID == "RdPdfs")
                {
                    lstName = PdfsUploadList;
                }
                if (((RadioButton)sender).ID == "RdVideos")
                {
                    lstName = VideosUploadList;
                }

                SPListItemCollection spListItemColl = SPContext.Current.Site.RootWeb.Lists[lstName].Items;
                DeleteItemsInDrpDown();

                if (spListItemColl.Count <= 0)
                {
                    SelectDropDown.Items.Add("No Files Uploaded under this Type");
                    btnUpload.Enabled = false;
                    SelectDropDown.SelectedIndex = 0;
                    SelectDropDown.Enabled = false;
                }
                else
                {
                    btnUpload.Enabled = true;
                    SelectDropDown.Enabled = true;
                    foreach (SPListItem itm in spListItemColl)
                    {
                        ListItem lstItem = new ListItem();
                        if (itm["Title"] != null && itm["Name"] != null)
                        {
                            lstItem.Text = (!itm["Title"].ToString().Contains('*')) ? itm["Title"].ToString() : itm["Title"].ToString().Split('*')[0];
                            lstItem.Value = itm["Name"].ToString();
                            SelectDropDown.Items.Add(lstItem);
 
                        }
                    }
                }
 
            }
 
        }

        private void customUploadValidator_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            List<string> allowedFileExtensions = new List<string>();

            string errorMessage = "Invalid File Extension, Valid extensions (";

            if (RdImages.Checked)
            {
                allowedFileExtensions.Add(".jpg");
                allowedFileExtensions.Add(".gif");
                allowedFileExtensions.Add(".bmp");
            }
            else if (RdVideos.Checked)
            {
                allowedFileExtensions.Add(".wmv");
                allowedFileExtensions.Add(".mpeg");
                allowedFileExtensions.Add(".mpg");
            }
            else if (RdPdfs.Checked)
            {
                allowedFileExtensions.Add(".pdf");
                allowedFileExtensions.Add(".doc");
                allowedFileExtensions.Add(".docx");
                allowedFileExtensions.Add(".xls");
                allowedFileExtensions.Add(".xlsx");
                allowedFileExtensions.Add(".ppt");
                allowedFileExtensions.Add(".pptx");
            }

            foreach (string str in allowedFileExtensions)
            {
                if (e.Value.ToLower().EndsWith(str))
                {
                    extFound = true;
                    break;
                }
                else
                {
                    extFound = false;
                    errorMessage += str + ' ';
                    continue;
                }
            }

            if (extFound)
            {
                e.IsValid = true;
            }
            else
            {
                customUploadValidator.ErrorMessage = errorMessage + " )";
                e.IsValid = false;
            }
 
        }

        private void UploadOrSelect(object sender, EventArgs e)
        {

            if (((RadioButton)sender).ID == "RdUpload")
            {
                btnUpload.Enabled = true;

                fileUploader.Visible = true;
                SelectDropDown.Visible = false;
                UploadRequiredValidator.Visible = true;

                FileNameTextBox.Visible = true;
                FileNameRequiredValidator.Visible = true;
                lblFileName.Visible = true;
            }
            else
            {
                object eventSender = null;

                fileUploader.Visible = false;
                SelectDropDown.Visible = true;
                UploadRequiredValidator.Visible = false;

                FileNameTextBox.Visible = false;
                FileNameRequiredValidator.Visible = false;
                lblFileName.Visible = false;

                if (RdImages.Checked)
                {
                    eventSender = RdImages;
                }
                if (RdPdfs.Checked)
                {
                    eventSender = RdPdfs;
                }
                if (RdVideos.Checked)
                {
                    eventSender = RdVideos;
                }
                FillInSelectDropDown(eventSender, e);
            }

        }
 
        private void UploadingGridRowDelete(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string deletedItmGuidId = string.Empty;
                string fileType = string.Empty;
                if (ViewState["UploadingGrid"] != null)
                {
                    DataTable dt = (DataTable)ViewState["UploadingGrid"];
                    DataRow dr = dt.Rows[e.RowIndex];
                    deletedItmGuidId = dr[3].ToString();
                    fileType = dr[1].ToString();
                    dt.Rows.RemoveAt(e.RowIndex);
                    UploadingGrid.DataSource = dt;
                    UploadingGrid.DataBind();
                    ViewState["UploadingGrid"] = dt;
                    DeleteItem(deletedItmGuidId, fileType);
                    CheckDataGrid();
                    CheckUploadStatus();
                }
            }
            catch
            {
                //To do: Log the Exception.
            }
        }

        private void DeleteItem(string deletedItmGuidId, string fileType)
        {

            string latestItemId = string.Empty;
            try
            {
                string lstName = string.Empty;
                if (fileType.ToLower() == "images")
                {
                    lstName = ImagesUploadList;
                }
                if (fileType.ToLower() == "pdf files")
                {
                    lstName = PdfsUploadList;
                }
                if (fileType.ToLower() == "videos")
                {
                    lstName = VideosUploadList;
                }
                SPQuery getDeletedItemQuery = new SPQuery();
                getDeletedItemQuery.Query = "" + deletedItmGuidId + "" + newsItemId + "";
                SPList spList = SPContext.Current.Site.RootWeb.Lists[lstName];
                SPListItemCollection coll = spList.GetItems(getDeletedItemQuery);
                getDeletedItemQuery = null;
                latestItemId = DeleteNewsIdFromItemTitle(coll);
 
                SPListItem itm = spList.GetItemById(coll[0].ID);
                spList.ParentWeb.AllowUnsafeUpdates = true;
                itm["Title"] = latestItemId;
                itm.Update();
                spList.Update();
                spList.ParentWeb.AllowUnsafeUpdates = false;
            }
            catch
            {
                //To do: Log the Exception.
            }

        }

        #endregion

        #region External helper functions
 
        private string DeleteNewsIdFromItemTitle(SPListItemCollection coll)
        {
            string[] strCollection;
            string latestItemId = string.Empty;
            try
            {
                if (coll.Count > 0 && coll[0]["Title"] != null)
                {
                    strCollection = coll[0]["Title"].ToString().Split('*');
                    foreach (string str in strCollection)
                    {
                        if (str.Trim() == newsItemId)
                        {
                            continue;
                        }
                        latestItemId += str + '*';
                    }
                    return latestItemId;
                }
                return string.Empty;
            }
            catch
            {
                //To do: Log the Exception.
                return string.Empty;
            }

        }
 
        private void FillInGridWithUploads()
        {
            try
            {
                if (Item[FileUploader.internalFieldName] != null)
                {
                    string newsItemId = this.Item[FileUploader.internalFieldName].ToString();
                    SPQuery getElementsByGuidId = new SPQuery();
                    getElementsByGuidId.Query = "" + newsItemId + "";
                    SPListItemCollection imagesCollection = SPContext.Current.Site.RootWeb.Lists[ImagesUploadList].GetItems(getElementsByGuidId);
                     SPListItemCollection videosCollection = SPContext.Current.Site.RootWeb.Lists[VideosUploadList
.GetItems(getElementsByGuidId);
 
                    SPListItemCollection pdfsCollection = SPContext.Current.Site.RootWeb.Lists[PdfsUploadList].GetItem
(getElementsByGuidId);
 
                    FillDataGrid(imagesCollection, pdfsCollection, videosCollection);
                    getElementsByGuidId = null;
                }
 
            }
            catch
            {
                //To do: Log the Exception.
            }
        }

        private void FillDataGrid(SPListItemCollection imagesCollection, SPListItemCollection pdfsCollection, SPListItemCollection videosCollection)
        {
            DataTable dt = new DataTable();
            DataColumn fileName = new DataColumn("File name");
            DataColumn fileType = new DataColumn("File type");
            DataColumn fileSize = new DataColumn("File size");
            DataColumn fileGuidId = new DataColumn("File guid id");
 
            dt.Columns.Add(fileName);
            dt.Columns.Add(fileType);
            dt.Columns.Add(fileSize);
            dt.Columns.Add(fileGuidId);

            foreach (SPListItem itm in imagesCollection)
            {
                DataRow row = dt.NewRow();
                if (itm["Title"] != null)
                {
                    row[fileName] = (!itm["Title"].ToString().Contains('*')) ? itm["Title"].ToString() : itm["Title"].ToString().Split('*')[0];
                }
                row[fileType] = "Images";
                row[fileSize] = itm.File.Length.ToString() + " bytes";
                row[fileGuidId] = (itm["Name"] != null) ? itm["Name"].ToString() : "";
                dt.Rows.Add(row);
            }
 
            foreach (SPListItem itm in pdfsCollection)
            {
                DataRow row = dt.NewRow();
                if (itm["Title"] != null)
                {
                    row[fileName] = (!itm["Title"].ToString().Contains('*')) ? itm["Title"].ToString() : itm["Title"].ToString().Split('*')[0];
                }
                row[fileType] = "pdf files";
                row[fileSize] = itm.File.Length.ToString() + " bytes";
                row[fileGuidId] = (itm["Name"] != null) ? itm["Name"].ToString() : "";
                dt.Rows.Add(row);
            }
            foreach (SPListItem itm in videosCollection)
            {
                DataRow row = dt.NewRow();
                if (itm["Title"] != null)
                {
                    row[fileName] = (!itm["Title"].ToString().Contains('*')) ? itm["Title"].ToString() : itm["Title"].ToString().Split('*')[0];
                }
                row[fileType] = "pdf files";
                row[fileSize] = itm.File.Length.ToString() + " bytes";
                row[fileGuidId] = (itm["Name"] != null) ? itm["Name"].ToString() : "";
                dt.Rows.Add(row);
            }

            UploadingGrid.DataSource = dt;
            UploadingGrid.DataBind();
            ViewState["UploadingGrid"] = dt;
        }

        private void AddSelectedToNewsItem()
        {
            string lstName = string.Empty;
            if (RdImages.Checked)
            {
                lstName = ImagesUploadList;
            }
            if (RdVideos.Checked)
            {
                lstName = VideosUploadList;
            }
            if (RdPdfs.Checked)
            {
                lstName = PdfsUploadList;
            }

            try
            {
                SPList list = SPContext.Current.Site.RootWeb.Lists[lstName];
                foreach (SPListItem itm in list.Items)
                {
                    if (itm["Name"] != null && itm["Name"].ToString().Contains(SelectDropDown.SelectedValue))
                    {
                        list.ParentWeb.AllowUnsafeUpdates = true;
                        itm["Title"] = itm["Title"].ToString() + '*' + newsItemId;
                        itm.Update();
                        list.Update();
                        list.ParentWeb.AllowUnsafeUpdates = false;
                        break;
                    }
                }
            }
            catch
            {
                //To do: Log Exception.
            }
        }

        private void AddUploadsToDocLib()
        {
            string listName = string.Empty;
            if (RdImages.Checked)
            {
                listName = ImagesUploadList;
            }
            else if (RdVideos.Checked)
            {
                listName = VideosUploadList;
            }
            else if (RdPdfs.Checked)
            {
                listName = PdfsUploadList;
            }

            try
            {
                //Get the Guid Id of the Item will be added to the List
                string itmGuidId = GetLastItemGuidId();

                SPContext.Current.Site.AllowUnsafeUpdates = true;
                SPFolder docLib = SPContext.Current.Site.RootWeb.GetFolder(listName);
                SPFile newFile = docLib.Files.Add(itmGuidId + '.' + fileUploader.FileName.Split('.')[1], fileUploader.FileBytes);
                newFile.Item["Title"] = FileNameTextBox.Text + '.' + fileUploader.FileName.Split('.')[1] + " * " +
newsItemId;
                newFile.Item.Update();
                docLib.Update();
 
                SPContext.Current.Site.AllowUnsafeUpdates = false;

            }
            catch
            {
                //To do: Log the Exception.
            }

        }

        private string GetLastItemGuidId()

        {
            string itmGuidId = string.Empty;
 
            if (ViewState["UploadingGrid"] != null)
            {
                DataTable dt = (DataTable)ViewState["UploadingGrid"];
                DataRowCollection drColl = dt.Rows;
                itmGuidId = drColl[dt.Rows.Count - 1][3].ToString();
 
            }
            return itmGuidId;
        }
 
        private void AddUploadsToUploadingGrid()
        {

            Button btnDeleteRow = new Button();
            DataTable dt = new DataTable();

            string fileTypeString = string.Empty;
            string lstName = string.Empty;
 
            try
            {
                if (ViewState["UploadingGrid"] != null)
                {
                    dt = (DataTable)ViewState["UploadingGrid"];
                }
                else
                {
                    DataColumn fileName = new DataColumn("File name");
                    DataColumn fileType = new DataColumn("File type");
                    DataColumn fileSize = new DataColumn("File size");
                    DataColumn fileGuidId = new DataColumn("File guid id");

                    dt.Columns.Add(fileName);
                    dt.Columns.Add(fileType);
                    dt.Columns.Add(fileSize);
                    dt.Columns.Add(fileGuidId);
                }
 
                DataRow dr = dt.NewRow();

                if (RdImages.Checked == true)
                {
                    fileTypeString = RdImages.Text;
                    lstName = ImagesUploadList;
                }
                if (RdPdfs.Checked == true)
                {
                    fileTypeString = RdPdfs.Text;
                    lstName = PdfsUploadList;
                }
                if (RdVideos.Checked == true)
                {
                    fileTypeString = RdVideos.Text;
                    lstName = VideosUploadList;
                }
 
                if (SelectDropDown.Visible == false)
                {
                    dr[0] = FileNameTextBox.Text;
                    dr[1] = fileTypeString;
                    dr[2] = fileUploader.PostedFile.ContentLength + " bytes";
                    dr[3] = Guid.NewGuid().ToString();
                }
                else
                {
                    SPListItem itm = GetSpecificFileFromDocLib(lstName, SelectDropDown.SelectedItem);
                    if (itm["Title"] != null)
                    {
                        dr[0] = (!itm["Title"].ToString().Contains('*')) ? itm["Title"].ToString() : itm["Title"].ToString().Split('*')[0];
                    }
                    dr[1] = fileTypeString;
                    dr[2] = itm.File.Length.ToString() + " bytes";
                    dr[3] = (itm["Name"] != null) ? itm["Name"].ToString() : "";
                }
 
                dt.Rows.Add(dr);
 
                UploadingGrid.DataSource = dt;
                ViewState["UploadingGrid"] = dt;
                UploadingGrid.DataBind();
 
                CheckDataGrid();
 
            }
            catch
            {
                //To do: Log the Exception.
            }
 
        }

        private SPListItem GetSpecificFileFromDocLib(string lstName, ListItem listItem)
        {
            foreach (SPListItem itm in SPContext.Current.Site.RootWeb.Lists[lstName].Items)
            {
                if (itm["Name"] != null && itm["Name"].ToString().Contains(listItem.Value))
                {
                    return itm;
                }
            }
            return null;
        }

        private void DeleteItemsInDrpDown()
        {
            int count = SelectDropDown.Items.Count;
            if (count > 0)
            {
                for (int i = 0; i < count; i++)
                {
                    SelectDropDown.Items.RemoveAt(0);
                }

            }
       }

         private string UpdateNewsItemID()
        {
            if (ControlMode == SPControlMode.New)
            {
                foreach (SPListItem itm in this.List.Items)
                {
                    if (itm[FileUploader.internalFieldName] != null && itm[FileUploader.internalFieldName].ToString() == newsItemId)
                    {
                        return Guid.NewGuid().ToString();
                    }
                }
                return newsItemId;
            }
            else if (ControlMode == SPControlMode.Edit)
            {
                if (this.Item[FileUploader.internalFieldName] != null && !string.IsNullOrEmpty(this.Item[FileUploader.internalFieldName].ToString()))
                {
                    return this.Item[FileUploader.internalFieldName].ToString();
                }
                else
                {
                    return Guid.NewGuid().ToString();
                }
             }
 
            return string.Empty;
 
        }

        private void CheckDataGrid()
        {
 
            if (!FileUploader.isRequired || (ViewState["UploadingGrid"] != null && ((DataTable)ViewState["UploadingGrid"]).Rows.Count > 0))
            {
                HiddenFieldGridValidator.Text = "New Item";
                FileNameRequiredValidator.Visible = false;
                UploadRequiredValidator.Visible = false;
            }
            else
            {
                HiddenFieldGridValidator.Text = string.Empty;
                GridValidator.Text = "No files uploaded yet.";
                FileNameRequiredValidator.Visible = true;
                UploadRequiredValidator.Visible = true;
            }

        }

        private void CheckUploadStatus()
        {
            int ImagesCount = 0;
            int VideosCount = 0;
            int PdfsCount = 0;
            EventArgs e = new EventArgs();
            object sender = null;

            if (ImagesMaximumLength == 0)
            {
                RdImages.Enabled = false;
            }
            if (VideosMaximumLength == 0)
            {
                RdVideos.Enabled = false;
            }
            if (PdfsMaximumLength == 0)
            {
                RdPdfs.Enabled = false;
            }

            if (ViewState["UploadingGrid"] != null && ((DataTable)ViewState["UploadingGrid"]).Rows.Count > 0)
            {
                CountImagesOfAType(ref ImagesCount, ref VideosCount, ref PdfsCount, (DataTable)ViewState["UploadingGrid"]);
            }
            if (ImagesCount >= ImagesMaximumLength)
            {
                RdImages.Checked = false;
                RdImages.Enabled = false;
            }
            else
            {
                RdImages.Enabled = true;
            }
 
            if (VideosCount >= VideosMaximumLength)
            {
                RdVideos.Enabled = false;
            }
            else
            {
                RdVideos.Enabled = true;
            }

            if (PdfsCount >= PdfsMaximumLength)
            {
                RdPdfs.Checked = false;
                RdPdfs.Enabled = false;
            }
            else
            {
                RdPdfs.Enabled = true;
            }

            if (RdImages.Enabled == true)
            {
                RdImages.Checked = true;
                sender = RdImages;
            }
            else if (RdImages.Enabled == false)
            {
                if (RdVideos.Enabled == true)
                {
                    RdVideos.Checked = true;
                    sender = RdVideos;
                }
                else
                {
                    if (RdPdfs.Enabled == true)
                    {
                        RdPdfs.Checked = true;
                        sender = RdPdfs;
                    }
                }
            }
            else if (RdVideos.Enabled == true)
            {
                RdVideos.Checked = true;
                sender = RdVideos;
            }
            else if (RdVideos.Enabled == false)
            {
                if (RdPdfs.Enabled == true)
                {
                    RdPdfs.Checked = true;
                    sender = RdPdfs;
                }
                else
                {
                    if (RdImages.Enabled == true)
                    {
                        RdImages.Checked = true;
                        sender = RdImages;
                    }
                }
            }
            else if (RdPdfs.Enabled == true)
            {
                RdPdfs.Checked = true;
                sender = RdPdfs;
            }
            else if (RdPdfs.Enabled == false)
            {
                if (RdImages.Enabled == true)
                {
                    RdImages.Checked = true;
                    sender = RdImages;
                }
                else
                {
                    if (RdVideos.Enabled == true)
                    {
                        RdVideos.Checked = true;
                        sender = RdVideos;
                    }
                }
            }

            FillInSelectDropDown(sender, e);

        }

        private void CountImagesOfAType(ref int ImagesCount, ref int VideosCount, ref int PdfsCount, DataTable dt)
        {
            string fileType = string.Empty;
            ImagesCount = 0;
            VideosCount = 0;
            PdfsCount = 0;

            foreach (DataRow row in dt.Rows)
            {
                if (row[1] != null)
                {
                    fileType = row[1].ToString().ToLower();
                }
                if (fileType == "Images".ToLower())
                {
                    ImagesCount++;
                }
                else if (fileType == "Videos".ToLower())
                {
                    VideosCount++;
                }
                else if (fileType == "pdf files".ToLower())
                {
                    PdfsCount++;
                }
            }

         }

        #endregion

    }
}