Reputation: 25
Something missing with the code (I guess). I want to show the student id and name in the list box. But I see this:
I can't figure out the problems especially with the inner join.
private void button1_Click(object sender, EventArgs e)
{
string strName = "";
connect.Open();
SqlCommand command = new SqlCommand(" Select Student_tbl.StudentName, Student_tbl.StudentID, Module_tbl.ModuleID FROM[Course-Student] INNER JOIN Student_tbl ON [Course-Student].SID = Student_tbl.StudentID INNER JOIN Module_tbl ON[Course-Student].CID = Module_tbl.ModuleID WHERE(Module_tbl.ModuleID = '" + tbCourse.Text+"')",connect);
command.ExecuteNonQuery();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
strName = reader[1].ToString();
listBox1.Items.Add(strName);
}
connect.Close();
}
Upvotes: 1
Views: 346
Reputation: 37299
You are printing retrieving from the reader only the StudentID
field. Change your while
loop as follows to retrieve both fields and concatenate the values:
while (reader.Read())
{
var name = reader[0].ToString();
var id = reader[1].ToString();
listBox1.Items.Add(id + " " + name);
}
You can also use String Interpolation (which is C# 6 syntactic sugar for string.Format
) like this:
while (reader.Read())
{
listBox1.Items.Add($"{reader[1].ToString()} {reader[0].ToString()}");
}
Also, as for the sql statement: Do not use string concatenation to create the statement. This is susceptible for SQL Injections. Use instead Parameterized Queries
Upvotes: 2