简体   繁体   中英

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 *

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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