该代码用于列表框控件,我喜欢用为gridview

本文关键字:我喜欢 gridview 控件 代码 用于 列表 | 更新日期: 2023-09-27 18:01:18

我曾看到过一篇地址如下的文章

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();

该代码用于列表框控件,我喜欢用为gridview

这是因为即使发现了重复的行,也不会停止添加新行。

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();

你只是嵌套错了-第一个循环应该是文件迭代,第二个循环-检查是否有重复。反之亦然

检查下面的代码片段:

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();
   }
}