在ASP.Net的Gridview控件中获取文件名的文件夹c#
问题描述:
我需要将文件夹中的文件名显示到GridView控件中。我想用目录类。在ASP.Net的Gridview控件中获取文件名的文件夹c#
在我的数据库我有列sFolder按每行在此值:
control/Imp/foo
我已经尝试了本tutorial在网络上,但我不能从一个文件夹获取文件名成GridView控件。
我没有错误,但即使文件夹路径正确,GridView也是空的。
我的代码如下。
你能帮我吗?
预先感谢您的任何帮助,非常感谢
的.cs
dt2 = new DataTable();
ds2 = new DataSet();
sql = @String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
的.aspx
<asp:GridView ID="gvDownload" EmptyDataText="Data empty"
runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
</asp:GridView>
#Edit 01
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
RetrieveProductsDowload();
}
private DataSet RetrieveProductsDowload()
{
dt2 = new DataTable();
ds2 = new DataSet();
sql = @String.Format(" SELECT * FROM tbl_2 WHERE sFolder IN ('control/Imp/foo'); ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["ConnMySQL"].ConnectionString))
{
using (OdbcCommand cmd =
new OdbcCommand(sql, cn))
{
OdbcDataAdapter adapter =
new OdbcDataAdapter(cmd);
adapter.Fill(ds2);
if (ds2.Tables.Count > 0)
{
dt2 = ds2.Tables[0];
FilePath = Server.MapPath("/myFolder/" + ds2.Tables[0].Rows[0]["sFolder"].ToString().Replace('/', '\\'));
Response.Write(FilePath);
// the response write FilePath is C:\inetpub\wwwroot\aspnet\myFolder\control\Imp\foo //
string[] filesLoc = Directory.GetFiles(FilePath);
List<ListItem> files = new List<ListItem>();
foreach (string file in filesLoc)
{
files.Add(new ListItem(Path.GetFileName(file)));
}
gvDownload.DataSource = files;
gvDownload.DataBind();
}
}
}
return ds2;
}
答
请试试这个:
string[] allfiles = Directory.GetFiles(FilePath, "*", SearchOption.AllDirectories);
gvDownload.DataSource = allfiles;
gvDownload.DataBind();
尝试:'gvDownload.DataSource = Directory.GetFiles(文件路径); gvDownload.DataBind();',使用'AutoGenerateColumns =“True”',并从GridView中删除' ... '。它工作吗? –
Ritesh
@Ritesh感谢你的回复,但不工作,GV是空的。 –
您是否在.cs文件中使用'Page_Load'来编写此代码? – Ritesh