SqlDataReader帮助显示读入不同标签文本的数据C#

SqlDataReader help for displaying the data that is read into the text of different labels C#

我对 SqlDataReader 的功能及其工作方式不是很有信心,我是否可以为找到的每个 StudentID 创建与 SQL 相对应的东西查询,它在不同的标签中显示每个 ID?如果可以,请您帮助我解决如何实现这一目标。

这是我目前使用 SQL 查询的代码:

private void SetTestsForm_Load(object sender, EventArgs e)
{
    string y = GlobalVariableClass.Signedinteacher;

    string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
    SqlConnection connect = new SqlConnection(connectionString);
    connect.Open();

    SqlCommand command20 = new SqlCommand(@"SELECT [StudentID] FROM StudentDetails WHERE ([TeacherID] = @signedinteacher)", connect);

    command20.Parameters.AddWithValue("@signedinteacher", y);

    SqlDataReader reader = command20.ExecuteReader(); 
}

你可以试试这个。

SqlDataReader oReader = new SqlDataReader();
            while (oReader.Read())
            {
                int oColumIndex = oReader.GetOrdinal("StudentID"); //Retrive the colunm index to get the data

                Label oLabel = new Label() { Text = oReader.GetString(oColumIndex) };//Get the data with the retrived colum index and set as Text of my
                                                                                     //label instance, the you can add this label in any container
            }

您可以借用 DataTable 中的 reader 并舍入 table 的行以检索所需字段的数据。

问候

您可以使用Properties

private int StudentID { get; set; }

然后在你的reader

using (SqlConnection con = new SqlConnection("Your Connection String"))
    {
        using (SqlCommand cmd = new SqlCommand("Your Query", con))
        {
            con.Open();
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    StudentID = Convert.ToInt32(reader["Field you want to read here"]);
                    YourLabelId.Text += StudentID;
                }
            }
        }

这是我的头等大事,所以请测试一下,但它应该能让您很好地理解