2016-10-17 3035 views
1

代码丢失(我猜)。我想在列表框中显示学生ID和姓名。但是,我看到这一点:如何打印从SQL Server数据库中检索到的2列

enter image description here

我想不通的问题,尤其是与内部联接。

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(); 
} 
+2

不要执行你的查询两次 - 首先用'command.ExecuteNonQuery()'(这里*完全没用*,因为你没有插入或删除任何东西),然后第二次用'.ExecuteReader()'。只调用** **真正需要的是 - 在这里:'ExecuteReader()',因为你要返回你想要迭代的结果集。 –

+0

谢谢..非常有帮助:) –

回答

2

您正在打印只读取StudentID字段中的检索项。更改while循环如下检索两个字段并连接所有的值:

while (reader.Read()) 
{ 
    var name = reader[0].ToString(); 
    var id = reader[1].ToString(); 
    listBox1.Items.Add(id + " " + name); 
} 

您也可以使用String Interpolation(这是string.Format C#6语法糖)是这样的:

while (reader.Read()) 
{ 
    listBox1.Items.Add($"{reader[1].ToString()} {reader[0].ToString()}"); 
} 

而且,对于sql语句:不要使用字符串连接来创建语句。这对SQL注入很敏感。改用Parameterized Queries

+0

不错..非常有帮助。主席先生,如何删除重复数据?例如MOD3--它显示我想要的所有列表,但如果我尝试搜索MOD2,MOD3的列表没有清除或删除。我做了一些研究,但我不太了解代码。我也制作清晰的按钮。 private void button2_Click(object sender,EventArgs e)// CLear BUtton { listBox1.Items.Clear(); } –

+0

@madhiahmahmod - 这是一个后续问题,应该在单独的问题中提出。如果你正在使用集合linq的'Distinct()'是一个很好用的东西。 –

相关问题