首页 > 解决方案 > 如何有一个列表有 n 个条目对按钮单击做出反应

问题描述

我有list我有图像位置路径的位置,并且我显示第一个 bt 我有这个button,当clicked我想移动到path列表的下一个时。我怎样才能做到这一点?

首先是我显示第一张图像的代码。

    protected void ShowPng(string pathPgnImg)
        {
            btnNextPage.Visible = true;
            string sImageName = "";
            
            string sImagePathImages = Server.MapPath("Anexos/");
            string pngFile = "";
            List<string> pngs = new List<string> { pngFile };
            string FileWithoutPath = Path.GetFileName(pathPgnImg);
            string fileWithoutPathAndExt = Path.GetFileNameWithoutExtension(FileWithoutPath);
            if(fileWithoutPathAndExt + "_pag" + LblHiddenImagePageNumber != fileWithoutPathAndExt + "_pag" + "" )
            {
                DirectoryInfo AnexoDirectory = new DirectoryInfo(PathForPdf);
                FileInfo[] filesInDir = AnexoDirectory.GetFiles(fileWithoutPathAndExt + "_pag" + "*.png");
                    
                
                    foreach (FileInfo foundFile in filesInDir)
                    {

                        pngFile = foundFile.FullName;
                        pngs.Add(pngFile);
                    }
                    pngFile = pngs[1];

            
                string sFileExt = Path.GetExtension(pngFile);

                pngFile = Path.GetFileNameWithoutExtension(pngFile);
                m_sImageNameUserUpload = pngFile + sFileExt;
                m_sImageNameGenerated = Path.Combine(sImagePathImages, 
                m_sImageNameUserUpload);

                //Literal1.Text += "<img src=" + '"' + pngFile + '"' + "/>";
                imgCrop.ImageUrl = "Anexos\\" + Path.GetFileName(pngFile);

                if (m_sImageNameUserUpload != "")
                {
                    pnlCrop.Visible = true;
                    imgCrop.ImageUrl = "Anexos/" + m_sImageNameUserUpload;
                    Session["ImageName"] = m_sImageNameUserUpload;
                }
            }
}

在 foreach 循环中,我将所有路径添加到List.

我想在这个按钮点击事件中实现这一点。

protected void btnNextPage_Click(object sender, EventArgs e)
        {
                     
            ShowPng(imgCrop.ImageUrl);
            
        } 

但是,如果有一种方法可以做到这一点,那么我就ShowPng function可以了。

标签: c#asp.netlist

解决方案


您需要某种状态变量来保存当前图像的索引,然后当您单击按钮时,您可以更新该状态。

我不认为您的 ShowPng 代码应该执行它的所有逻辑。

您应该在一个方法中找到在路径中找到的所有图像,并再次显示它们,这应该存储在某个类级别的属性或状态对象中。

private List<string> imagePaths = new List<string>();
private int imageIndex = 0;

在您包含的方法中,当您找到匹配的图像时,将一个项目添加到 imagePaths 列表中。然后,当您单击下一个按钮时,您将执行以下操作-

imageIndex++ //increase index by 1
imageCrop.ImageUrl = imagePaths[imageIndex]

推荐阅读