0

我有一个用户表(tblUsers),其中包含大学工作人员的详细信息。我正在尝试使用与所选模块关联的讲师姓名填充文本框。

我正在获取与特定模块关联的所有用户 ID,测试用户是否是讲师,如果是,那么我将 ID 添加到 ArrayList。

然后我遍历这个数组,并在每次遍历当前 ID 的过程中调用下面的方法。

但是,如果您查看下面的方法,我正在使用 SqlDataReader 并且在从该行读取时遇到错误:

txtLecturerName.Text += myReader["First_Name"].ToString();

错误消息是:'myReader["First_Name"]' 引发了类型为 'System.IndexOutOfRangeException' 的异常

我使用的表格布局在方法代码下方。对此的任何帮助将不胜感激,我只需一杯咖啡就可以将头穿过屏幕。

public void outputLecturerNames(string lecturerID)
{
    // Create a new Connection object using the connection string
    SqlConnection myConnection = new SqlConnection(conStr);

    // If the connection is already open - close it
    if (myConnection.State == ConnectionState.Open)
    {
        myConnection.Close();
    }

    // 'using' block allows the database connection to be closed
    // first and then the exception handling code is triggered.
    // This is a better approach than using a 'finally' block which
    // would close the connection after the exception has been handled.
    using (myConnection)
    {
        try
        {
            // Open connection to DB
            myConnection.Open();

            SqlCommand selectCommand = new SqlCommand(selectQuery, myConnection);

            // Declare a new DataReader
            SqlDataReader myReader;

            selectQuery = "SELECT * FROM tblUsers WHERE User_ID='";
            selectQuery += lecturerID + "'";

            myReader = selectCommand.ExecuteReader();

            while (myReader.Read())
            {
                txtLecturerName.Text += myReader["First_Name"].ToString();
                txtLecturerName.Text += " ";
                txtLecturerName.Text += myReader["Last_Name"].ToString();
                txtLecturerName.Text += " , ";
            }
            myReader.Close();
        }
        catch (Exception err)
        {
            Console.WriteLine("Error: " + err);
        }
    }
}

tbl用户:

[User_ID][First_Name][Last_Name][Email_Address]
4

3 回答 3

3

在您的方法中,未声明变量 selectQuery,它在 tblUsers 上分配查询字符串之前用作 SqlCommand 的参数。

于 2010-07-20T17:05:44.197 回答
0

您可能拼错了列名。

一般来说,你永远不应该写SELECT * FROM ....
相反,您应该只选择您需要的列。

这将通过仅查询您需要的信息来使您的程序运行得更快,并且可以产生更好的错误消息。

于 2010-07-20T16:53:38.590 回答
0

当未找到给定的列名时会创建此错误。如果你和我一样,你可能已经检查过好几次了,但是表名是否正确(正确的数据库、正确的架构)以及列名是否正确?

http://msdn.microsoft.com/en-us/library/f01t4cfy.aspx

您可以尝试完全限定表的名称 (database.dbo.tblUsers)。这将确保您击中您认为的牌桌。此外,尝试将列名放入 SQL 语句中。如果它们不正确,您的 SQL 语句将无法正确执行。

于 2010-07-20T16:55:29.530 回答