System.IndexOutOfRangeException 错误 SQL SELECT 查询无法读取从我的 table 中选择的数据

System.IndexOutOfRangeException error SQL SELECT query unable to read the data selected from my table

我在 SQL 上有我的 SELECT 声明,我只是想查看从 table 检索到的内容以检查它是否正常工作,但是我有 运行陷入困境!

我不确定为什么我的代码不起作用,每当我尝试 运行 代码时,就会出现一个错误:System.IndexOutOfRangeException,我似乎找不到解决这个问题的方法。

如有任何帮助,我将不胜感激!

public partial class CurrentlySetTestForm : Form

{
    Timer loopTimer = new Timer();
    private string CurrentQuestionID { get; set; }
    private string QuestionSpace { get; set; }
    public CurrentlySetTestForm()
    {
        InitializeComponent();
    }

    private void CurrentlySetTestForm_Load(object sender, EventArgs e)
    {

        string y = GlobalVariableClass.Signedinteacher;

        Convert.ToInt32(y);

        string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
        SqlConnection connect = new SqlConnection(connectionString);

        connect.Open();

        SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) FROM QuestionStudentAssociation WHERE ( [StudentID]=@Signedinstudent AND [StudentAnswer]=NULL )", connect);
        command18.Parameters.AddWithValue("@Signedinstudent", y);

        var reader = command18.ExecuteReader();
        while (reader.Read())
        {
            CurrentQuestionID = reader["QuestionID"].ToString();
            MessageBox.Show(CurrentQuestionID);

        }

         }
    }

你的错误来自这一行:

CurrentQuestionID = reader["QuestionID"].ToString();

因为您的查询没有返回 ID 为 "QuestionID" 的字段,因为您正在查询其最小值 "MIN([QuestionID])"

最简单的修复方法是:

 CurrentQuestionID = reader[0].ToString();

这使用值的索引而不是按字段名索引。

按照@KasparsOzols 的建议,另一种方法是通过像这样更改您的查询来适当地命名您的 "MIN" 字段值:

var qryText = "SELECT MIN([QuestionID]) AS MinQuestionID FROM QuestionStudentAssociation WHERE (StudentID]=@Signedinstudent AND [StudentAnswer] IS NULL)"
SqlCommand command18 = new SqlCommand(qryText, connect);

然后像这样检索您的字段:

CurrentQuestionID = reader["MinQuestionID"].ToString();

正如@KasparsOzols 也指出的那样,您的 SQL 语句中存在错误。您不能使用“=NULL”检查 "NULL",而是使用 "IS NULL".

原因是您的 MIN 函数调用。它不是 return 作为列名 QuestionID,你用 reader["QuestionID"] 来调用它。 Min returns 是一个未命名的列。尝试

SELECT MIN([QuestionID]) as QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=@Signedinstudent AND [StudentAnswer]=NULL )

应该可以了。