基本上,我有这个学生列表(alunos),我想双击其中一个学生,并希望它显示一个包含以下内容的MessageBox:
Student No.: {student no. from the selected student here}
Name: {student name from the selected student here}
etc...
这是我的代码:
void lstAlunos_MouseDoubleClick(object sender, MouseEventArgs e)
{
string query = "SELECT * FROM (" +
"SELECT" +
"ROW_NUMBER() AS rownumber," +
"columns" +
"FROM Alunos" +
") AS foo" +
"WHERE rownumber = " + lstAlunos.SelectedIndex;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (var reader = command.ExecuteReader())
{
connection.Open();
reader.Read();
string numAluno = reader.GetString(0);
string nomeAluno = reader.GetString(1);
string apelidoAluno = reader.GetString(2);
string contactoAluno = reader.GetString(3);
string emailAluno = reader.GetString(4);
}
int index = this.lstAlunos.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show("Nome: " + nomeAluno);
}
}
答案 0 :(得分:1)
在要连接的字符串的末尾添加空格。现在,此段:
"columns" +
"FROM" +
会给您“ columnsFROM”,这显然是不好的SQL。
其他一些建议:
ROW_NUMBER()
。不能保证您将获得的行与以前保存时的顺序相同。请改用ID列。