如何创建 foreach 语句以确定所选索引值是否为“0”

How do I create a foreach statment to determine if the selected index value is "0"

我有一个下拉列表,当用户从下拉列表中选择一个视频时,它将加载一个视频。我在下拉列表的索引 0 中插入了一个空值,因此没有预选视频。在用户重新选择第一个项目之前,这非常有用。该应用程序尝试加载此不存在的视频。我想创建一个 foreach 循环,如果所选索引为 0,我想跳出而不尝试加载视频。

我在 break 和 continue 行都遇到了这个错误 "no enclosing loop out to which to continue or break"。

感谢您的提前协助。

  protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
  {
    string YourFilePathWithFileName = DropDownList1.SelectedValue;

        foreach (int DropDownList1_SelectedIndexChanged in DropDownList1.SelectedIndex)
        if (DropDownList1.SelectedIndex.Equals(0))

        {
          break;

          media_video.Attributes.Add("src", "/Uploads/" + YourFilePathWithFileName + ".mp4");
          media_video.Attributes.Add("type", "video/mp4");
          media_video.Attributes.Add("autoplay", "autoplay");
          media_video.Attributes.Add("src", "/Uploads/" + YourFilePathWithFileName + ".ogc");
          media_video.Attributes.Add("type", "video/ogv");
          media_video.Attributes.Add("autoplay", "autoplay");
          media_video.Attributes.Add("src", "/Uploads/" + YourFilePathWithFileName + ".webm");
          media_video.Attributes.Add("type", "video/webm");
          media_video.Attributes.Add("autoplay", "autoplay");
        }
      }

您的代码不在任何循环内,因此它抱怨无法从代码块中 breakcontinue( cz 它没有找到任何)。据我了解你的问题你只是不想加载视频或者更确切地说添加属性到 media_video (技术上)你可以简单地检查索引并像这样跳过这个过程:-

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   if (DropDownList1.SelectedIndex != 0)
   {
      string YourFilePathWithFileName = DropDownList1.SelectedValue;
      media_video.Attributes.Add("src", "/Uploads/" + YourFilePathWithFileName + ".mp4");
      media_video.Attributes.Add("type", "video/mp4");
      ..other attributes
   }
   else
   {
      media_video.Attributes.Remove("src");
   }
} 

您不必为您的问题使用任何循环。如果我理解正确,如果用户将选择索引为 0 的视频,则您想停止视频加载或显示一些默认视频。你的代码应该是这样的:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
    {
      media_video.Attributes.Add("src", "/Uploads/" + DefaultVideo + ".mp4");
      media_video.Attributes.Add("type", "video/mp4");
      media_video.Attributes.Add("autoplay", "autoplay");
      media_video.Attributes.Add("src", "/Uploads/" + DefaultVideo + ".ogc");
      media_video.Attributes.Add("type", "video/ogv");
      media_video.Attributes.Add("autoplay", "autoplay");
      media_video.Attributes.Add("src", "/Uploads/" + DefaultVideo + ".webm");
      media_video.Attributes.Add("type", "video/webm");
      media_video.Attributes.Add("autoplay", "autoplay");
    }
  }

如果您不需要做任何事情,只需关闭您的视频控件(它将禁用您的视频控件):

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
    {
       media_video.Visible = false;
    }
  }

希望对您有所帮助