<pre lang="msil"> private void Button_Click(object sender, EventArgs e) { string strConnectionString = "Server=M;Database=ADO;UID=..; PWD=...;"; Button btnCurrent = (Button)sender; switch (btnCurrent.Name) { case "btnInsert": { string strQuery = "INSERT INTO authors (au_id, au_fname, au_lname)" + "VALUES (@au_id, @au_lname, @au_fname)"; SqlConnection connection = new SqlConnection(strConnectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.Text; command.CommandText = strQuery; command.Connection = connection; try { command.Parameters.AddWithValue("au_id", txtID.Text); command.Parameters.AddWithValue("au_fname", txtFirstName.Text); command.Parameters.AddWithValue("au_lname", txtLastName.Text); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("It's Done"); } catch (SqlException sqlEX) { MessageBox.Show(sqlEX.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (connection.State != ConnectionState.Closed) connection.Close(); connection.Dispose(); } break; } case "btnShow": { string strQuery = "SELECT au_id,au_fname,au_lname FROM authors"; SqlConnection connection = new SqlConnection(strConnectionString); SqlCommand command = new SqlCommand(); SqlDataReader reader = null; command.CommandType = CommandType.Text; command.CommandText = strQuery; command.Connection = connection; lstContact.Items.Clear(); try { connection.Open(); reader = command.ExecuteReader(); while (reader.Read()) { string strID = reader[0].ToString(); string strFirstName = reader[1].ToString(); string strLastName = reader[2].ToString(); ListViewItem item = new ListViewItem(strID); item.SubItems.Add(strFirstName); item.SubItems.Add(strLastName); lstContact.Items.Add(item); } } catch (SqlException sqlEX) { MessageBox.Show(sqlEX.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if (reader != null) { if (! reader.IsClosed) { reader.Close(); } reader.Dispose(); } command.Dispose(); if (connection.State != ConnectionState.Closed) connection.Close(); connection.Dispose(); } break; } default: break; } } } }
<br /> lstContact.DataBind();<br />
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)