【问题标题】:SqlDataReader help for displaying the data that is read into the text of different labels C#SqlDataReader 帮助显示读入不同标签文本的数据 C#
【发布时间】:2015-07-03 02:01:37
【问题描述】:

我对@9​​87654322@ 的功能及其工作方式不是很有信心,我是否可以为每个找到的与 SQL 查询对应的StudentID 创建一些东西,它将每个 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(); 
}

【问题讨论】:

  • 如果您在此问题上找到“部分员工”(答案)(本评论末尾的网址)......您将找到一种更“分层”的方法来解决您的问题。在您设计软件时,我会搜索“分层应用程序”。 stackoverflow.com/questions/13650443/…

标签: c# sql sql-server select label


【解决方案1】:

你可以试试这个。

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 中的阅读器,然后对表中的行进行四舍五入,以检索所需字段的数据。

问候

【讨论】:

  • 在同一个代码块中看到 UI 对象(标签)和 IDataReader 会伤害我的眼睛。
  • 为什么?我知道他想为每行创建一个标签,我正在解释如何阅读读者,我不是在制作应用程序,我只是在解释兄弟。
  • 我明白你的意思。你给他一个快速演示。但这没有被注意到。因此,与 DB 层代码混合的 UI 可能会成为他的最终解决方案……因为没有向他指出“层”的概念……这就是速成示例他/她被给予了。
  • 呵呵呵呵,是的,他/她必须知道混合这些层不是一个好习惯。感谢您的评论。
【解决方案2】:

您可以使用Properties

private int StudentID { get; set; }

然后在你的阅读器中

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;
                }
            }
        }

这是在我的头上,所以请测试它,但它应该能让你很好地理解

【讨论】:

  • 好的,非常感谢您的帮助,它有效!现在我在代码的不同部分发现了一个错误:@
  • 不客气!如果错误与此问题无关,也许考虑问另一个问题
猜你喜欢
  • 2014-10-30
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2021-09-13
  • 2021-12-05
相关资源
最近更新 更多