我看过1篇关于以下地址的文章
http://www.c-sharpcorner.com/UploadFile/rohatash/uploading-multiple-files-with-listbox-in-Asp-Net/
用于显示上传文件的使用列表框
if (ListBox1.Items.Contains(new ListItem(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName))))
{
Label1.Text = "File already in the ListBox";
}
else
{
Files.Add(FileUpload1);
ListBox1.Items.Add(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName));
Label1.Text = "Add another file or click Upload to save them all";
}
,现在我喜欢在网格视图中执行此操作,但我在网格视图下面的代码转移时遇到问题,它有问题,它不会阻止重复上传的文件。
for (int i = 0; i < count; i++)
{
if (GridViewEfile.Rows[i].Cells[1].Text == FileName)
{
Label2.Text = "File already in the list";
break;
}
}
我为gridview做了什么:
for (int i = 0; i < count; i++)
{
if (GridViewEfile.Rows[i].Cells[1].Text == FileName)
{
Label2.Text = "File already in the list";
break;
}
}
for (int j = 0; j < count; j++)
{
dr = dt.NewRow();
dr["File Name"] = GridViewEfile.Rows[j].Cells[1].Text;
dr["File Size"] = GridViewEfile.Rows[j].Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["File Name"] = FileName;
if (size > 0)
dr["File Size"] = size.ToString() + " KB";
else
Label2.Text = "File size cannot be 0";
dt.Rows.Add(dr);
GridViewEfile.DataSource = dt;
GridViewEfile.DataBind();
答案 0 :(得分:0)
这是因为即使找到重复行也不会停止添加新行。
bool isDuplicate = false;
for (int i = 0; i < count; i++)
{
if (GridViewEfile.Rows[i].Cells[1].Text == FileName)
{
Label2.Text = "File already in the list";
isDuplicate = true;
break;
}
}
for (int j = 0; j < count; j++)
{
dr = dt.NewRow();
dr["File Name"] = GridViewEfile.Rows[j].Cells[1].Text;
dr["File Size"] = GridViewEfile.Rows[j].Cells[2].Text;
dt.Rows.Add(dr);
}
if (!isDuplicate)
{
if (size == 0)
{
Label2.Text = "File size cannot be 0";
}
else
{
dr = dt.NewRow();
dr["File Name"] = FileName;
dr["File Size"] = size.ToString() + " KB";
dt.Rows.Add(dr);
}
}
GridViewEfile.DataSource = dt;
GridViewEfile.DataBind();
答案 1 :(得分:0)
你只是有错误的嵌套 - 第一个循环应该是文件迭代,第二个循环 - 检查欺骗。反过来也是如此。
检查以下代码段:
for (int j = 0; j < count; j++) // here is file iteration
{
for (int i = 0; i < count; i++) // here is dupe check
{
if (GridViewEfile.Rows[i].Cells[1].Text == FileName)
{
Label2.Text = "File already in the list";
break;
}
}
dr = dt.NewRow();
dr["File Name"] = FileName;
if (size > 0)
dr["File Size"] = size.ToString() + " KB";
else
Label2.Text = "File size cannot be 0";
dt.Rows.Add(dr);
GridViewEfile.DataSource = dt;
GridViewEfile.DataBind();
}
}