2010年7月7日星期三
把图片文件夹中的子文件夹以下拉框的形式展示出来。并且选择不同的文件夹显示出各文件夹中的图片。
前台页面:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<%
Response.Write("the line is : <br/>");
for (int i = 0; i < strFiles.Length; ++i)
{
Response.Write("<li><img src=/"images/" + getShortFileNameAndDir(strFiles[i]) + "/"" + " alt=/"/" width=/"76/" height=/"76/" /></li>");
}
%>
</div>
</form>
后台页面:
using System.IO; //path
using System.Text; //stringbuilder
public string[] strFiles; //这是每个子文件夹目录。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strPath;
string[] strFilesOfDirectory;
string strFile;
strPath = Path.GetDirectoryName(Server.MapPath("showimages"));
//Response.Write("strpath:" + strPath);
//Response.Write("<br />");
strPath += "//" + "images";
strFilesOfDirectory = Directory.GetDirectories(strPath);
for (int i = 0; i < strFilesOfDirectory.Length; ++i)
{
DropDownList1.Items.Add(getShortDirectory(strFilesOfDirectory[i]));
}
//进行第一初始化
DropDownList1_SelectedIndexChanged(sender, e);
}
}
/// <summary>
/// 获得短文件夹路径,也就是文件夹名
/// </summary>
/// <param name="strDir"></param>
/// <returns></returns>
public string getShortDirectory(string strDir)
{
int ind = strDir.LastIndexOf("//");
return strDir.Substring(ind+1);
}
/// <summary>
/// 获得图片的带文件夹的路径
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public string getShortFileNameAndDir(string str)
{
string shortname = getShortDirectory(str);
return DropDownList1.Text + "/"+ shortname;
}
/// <summary>
/// 动态加载图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strPath;
string strFile;
strPath = Path.GetDirectoryName(Server.MapPath("showimages"));
strPath += "//" + "images";
strPath += "//" + DropDownList1.Text;
strFiles = Directory.GetFiles(strPath);
for (int i = 0; i < strFiles.Length; ++i)
{
Response.Write("文件名:");
Response.Write(strFiles[i]);
Response.Write("<P>");
}
}