简体   繁体   English

在C#中从数据库显示文本框中的数据

[英]Show data in Textboxes from database in C#

Is there anything wrong with my code? 我的代码有什么问题吗? It is not showing data in textboxes. 它不在文本框中显示数据。 The same funtion is working for another table in database but not for this one. 相同的功能适用于数据库中的另一张表,但不适用于此表。

private void metroButton1_Click(object sender, EventArgs e)
    {
        con = new SqlConnection(constr);

        String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";

        cmd = new SqlCommand(query, con);

        con.Open();
        try
        {
            using (SqlDataReader read = cmd.ExecuteReader())
            {
                while (read.Read())
                {
                    // metroTextBox1.Text = (read["ID"].ToString());
                    metroTextBox2.Text = (read["Name"].ToString());
                    metroTextBox3.Text = (read["F_Name"].ToString());
                    metroTextBox4.Text = (read["Std_Age"].ToString());
                    metroTextBox5.Text = (read["Address"].ToString());
                    metroTextBox6.Text = (read["Program"].ToString());
                    metroComboBox1.Text = (read["Course"].ToString());

                }
            }
        }
        finally
        {
            con.Close();
        }
    }

you need to give column names in the select statement or select * 您需要在select语句中提供列名选择*

for example : 例如 :

 String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";

Not related to Question: you can change the while loop to if condition if you have one record for given id. 与问题无关:如果您有给定ID的一条记录,则可以将while循环更改为if条件。 even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record. 即使给定ID的记录很多,您也只会看到最后一条记录的数据,因为while循环会覆盖每条记录中的文本框。

Update : 更新:

There isn't anything wrong with Syntax because the same syntax is working for modifying teacher funtion. 语法没有任何问题,因为相同的语法可用于修改教师功能。

No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error 不,这是不正确的,删除​​代码中的try catch,然后会看到syntax error的异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM