我希望创建一个使用“拖放”问题的测验,其中涉及用户将标签拖动到pictureBox,如果它们都匹配,则两者都将消失并且分数将更新。 为了实现这一点,我使用了类来添加多个问题。 但是,发生运行时错误,并且我不知道如何解决它,因为它会阻止程序运行并导致出现相应的图片和标签
public partial class DragNDropQuestions : Form
{
public DragNDropQuestions()
{
InitializeComponent();
AllowDrop();
SetupQuestions();
lblScore.Text = "Score: " + itemsleft;
}
int itemsleft = 0;
private List<DragNDropClass> questions = new List<DragNDropClass>();
private int _currentQuestion = 0;
private void SetupQuestions()
{
questions.Add(new DragNDropClass(new[] {"Red","Blue","Yellow"},new[] {Image.FromFile("../../Resources/Blue.jpg"),Image.FromFile(" ../../Resources/Red.jpg"),Image.FromFile("../../Resources/Yellow.jpg") },new[] { "Blue", "Red", "Yellow" }));
NextQuestion();
}
private void AllowDrop()
{
pictureBox1.AllowDrop = true;
pictureBox2.AllowDrop = true;
pictureBox3.AllowDrop = true;
}
private void DragNDropQuestions_Load(object sender, EventArgs e)
{
}
private void LabelGrabbed(object sender, DragEventArgs e)
{
Label selectedlabel = (Label)sender;
selectedlabel.DoDragDrop(selectedlabel.Text, DragDropEffects.Copy);
}
private void NextQuestion()
{
string[] labels = questions[_currentQuestion].LabelClass;
Image[] pictures = questions[_currentQuestion].PictureBox;
Random random = new Random();
int rand = random.Next(0, 2);
label1.Text = labels[0];
label2.Text = labels[1];
label3.Text = labels[2];
pictureBox1.Image = (pictures[0]);
pictureBox2.Image = (pictures[1]);
pictureBox3.Image = (pictures[2]);
}
private void AnswerUpdate(object sender,DragEventArgs e)
{
string[] result = (string[])e.Data.GetData(DataFormats.Text);
if (_currentQuestion < questions.Count - 1)
{
if (result == questions[_currentQuestion].CorrectAnswers)
{
itemsleft++;
lblScore.Text = "Score: " + itemsleft;
}
}
}
private void PictureBox2_Click(object sender, EventArgs e)
{
}
private void AllowDragDropCopy(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void WindowsDragDrop(object sender, DragEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
如何克服这个问题并继续进行测验? 这是错误: enter image description here
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
答案 0 :(得分:0)
我认为可能是" ../../Resources/Red.jpg"
开头的流氓空间在这里引起了问题。
如果这没有帮助,那么如果没有更多信息,很难确定,但是看起来问题出在寻找图像位置。这可能是因为路径是相对的。它们将被视为相对于当前工作文件夹的,这可能与执行程序集的位置不同。
要调试此功能,建议您首先尝试评估图像的绝对路径。您可以尝试以下操作:
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
var exePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
var absolutePath = Path.GetFullPath("../../Resources/Red.jpg");
测试此代码应有助于您找出问题所在。