Listing directory files in Dropdownlist with .Net
July 26, 2007Just recently, I was asked to develop a video and audio gallery with either php or .net including the CMS side of it. Having very little experience in php, I opted to develop in .net. Now comes bit of analysis part, taking into consideration that upload file more then 5mb with CMS through Http will take lots of time and plus there are other problems such as connection timeouts due to low transfer rates, etc.
However, I have come up with another idea i.e. I will ask the users to upload files to the appropriate directory using FTP. Then with the help of CMS which makes an entry to the DB, select the file and make an entry.
The problem was when I tried to list files in a directory with a Listbox using following code:
//set directory and array
ArrayList values = new ArrayList();
//get files
protected string dirPath;
protected int dirPathLength;
//get filenames
protected String [] files;
//get files
dirPath = Server.MapPath(”../audiofiles/”);
dirPathLength = dirPath.Length;
dirPathLength = dirPathLength+1;
files = Directory.GetFiles(dirPath, “*.flv”);
//iterate through list, replace path info, and add to the listbox with the Add method.
for(int i=0;i<files.Length;i++)
{
string FileName = files[i];
FileName = FileName.Replace(Server.MapPath(”../audiofiles/”),”");
values.Add (FileName);
}
//bind data to listbox’s datasource
ListBox.DataSource = values;
ListBox.DataBind();
This lists files very well but when I try to make an entry to the DB with
ListBox.SelectedValue
Attribute just simply does not select the selected value. I tried all the methods but with no success. So assuming that either I am doing something wrong or there is a bug in the ListBox.SelectedValue attribute.
Now with regards to time constraint, I decided to use Dropdownlist which works just fine. Just add a Dropdownlist and make changes to following last two lines in above code
//bind data to Dropdownlist datasource
Dropdownlist.DataSource = values;
Dropdownlist.DataBind();
and
Dropdownlis.SelectedValue works
Hope, this works for anyone interested but if there is anyone with an opinion about ListBox’s SelectedValue attribute please send in your comments.
Posted by Vishal Reddy