我有一个用户表(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]