In WinForm database design, it is sometimes necessary to query the corresponding data by condition, and display the data in the text box (or Rich text box), below, the small series will tell through a condition:
First, we need to make a connection to the database and execute the database command, before we create a WinForm form that looks like this:
After creating the form, we should write the code phase:
1 strings ="server=sam_pc;database=minformationdb;integrated security=true";2SqlConnection con =NewSqlConnection (s);3 con. Open ();4 stringsql =string. Format ("SELECT * from Student where grade= ' {0} '", TextBox1.Text);5SqlCommand Command =NewSqlCommand (sql, con);6 7SqlDataReader reader =command. ExecuteReader ();8 while(reader. Read ())9 {Ten stringid = (String) reader["Id"]; One stringName = (String) reader["Name"]; A intAge = (int) reader[" Age"]; - stringGender = (string) reader["Gender"]; - stringMajor = (string) reader["Major"]; theTextBox2.Text + = String.Format ("{0}\t{1}\t{2}\t{3}\t{4}\r\n", ID, name, age, gender, major); -}
---->
SKILLS:
-----------you need to read the returned data using DataReader when the query result may return more than a row or columns
The function of DataReader is to read the data from one row at a time:-----------Read method: Reads a row of data from the database, returns BOOL, evaluates to TRUE to read the data, false indicates that all reads have been completed, and that no number of readings have been made. -----------[column name]: Gets the value of a field in the current row, returns the type of object, typically a type conversion-----------close: Closes after use, frees the resource to read the data:-----------(0) Create a connection, create a command, Open Connection previous-----------(1) SqlCommand.ExecuteReader returns a SqlDataReader object-----------(2) The Sqldatareader.read method reads a row of data-----------(3) sqldatareader["column name"] reads a column of the current row, is type object, requires a type conversion-----------(4) repeat (3) Steps to read other fields-----------(5) go to (2) read the next row of data
C # WinForm Form design-querying data by criteria