private void Button3_Click (object sender, EventArgs e)
{
String sql = "Select Dname,did from department";
SqlConnection conn = new SqlConnection ("Data source= (local); Initial catalog=hem09; User Id=sa; password=123456 ");
Try
{
SqlCommand cmd = new SqlCommand (SQL, conn);
Conn. Open ();
SqlDataReader reader= cmd. ExecuteReader ();
Bind data to a list box
CboList.Items.Clear ();
Iterate through each row of data
while (reader. Read ())//deferred execution
{
Using indexers to read data
READER[1]
reader["Dname"]
Read in a way that does not require a type conversion
String Dname=reader. GetString (0);//Index of column for parameter
Note: The index here is not determined based on the structure of the table, but rather on the result set of the SELECT clause.
CBOLIST.ITEMS.ADD (dname);
}
Reader. Close ();
Reader. Dispose ();
Cmd. Dispose ();
Cmd.commandtext = "";
}
Catch
{
//...
}
Finally
{
Conn. Close ();
Conn. Dispose ();
}
}
private void Cbtitle_selectedindexchanged (object sender, EventArgs e)
{
TextBox1.Text = CbTitle.SelectedItem.ToString ();//drop-down box value passed into other components
}
private void Button4_Click (object sender, EventArgs e)
{
String sql = "Select Dname,did from department";
using (SqlConnection conn = new SqlConnection ("Data source= (local); Initial Catalog=hem09;user Id=sa; password=123456 "))
{
SqlCommand cmd = new SqlCommand (SQL, conn);
Conn. Open the connection as late as possible, close the connection as early as you could
SqlDataReader reader = cmd. ExecuteReader ();
Bind data to a list
CboList.Items.Clear ();
while (reader. Read ())
{
Department D1 = new Department () {Did=reader. GetInt32 (1), Dname=reader. GetString (0)};
CBOLIST.ITEMS.ADD (D1);
Cbolist.displaymember = "dname";//a property of the specified object is used to display
}
Reader. Close ();
Reader. Dispose ();
}
}
private void Button5_click (object sender, EventArgs e)
{
1. Construct SQL statements
String sql = "SELECT * from department";
2 Establishing the connection
using (SqlConnection conn = new SqlConnection ("Data source= (local); Initial catalog=hem09; User Id=sa; password=123456 "))
{
3.1 Constructing a Command object
SqlCommand cmd = new SqlCommand (SQL, conn);
2.1 Opening the connection
Conn. Open ();
3.2 Execute Command
using (SqlDataReader reader = cmd. ExecuteReader ())
{
Empty the original data
GvList.Rows.Clear ();
GvList.Columns.Clear ();
New column
GVLIST.COLUMNS.ADD ("Did", "number");
GVLIST.COLUMNS.ADD ("Dname", "name");
Iterate through the query result set to add data to the list
while (reader. Read ())
{
Department D1 = new Department () {did = reader. GetInt32 (0), dname = reader. GetString (1)};
GVLIST.ROWS.ADD (D1. did, D1. DNAME);
}
}
Cmd. Dispose ();
}
}
Combox binding Data