0

我看过 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();
4

2 回答 2

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();
于 2013-02-27T14:42:05.170 回答
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();
   }
}
于 2013-02-27T14:42:47.190 回答