using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace ch11_3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string conStr;
            conStr = "Data Source=va-pc;Initial Catalog=University;Integrated Security=True";
            SqlConnection connect = new SqlConnection(conStr);
            connect.Open();
            SqlCommand cmd = null;
            cmd = new SqlCommand("selectProc", connect);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataReader rdr = cmd.ExecuteReader();
            string record = "Record not found" ;
            while (rdr.Read())
            {
                   record = "";
                   record += rdr["studentId"].ToString() + " ";
                   record += rdr["firstName"].ToString() + " ";
                   record += rdr["lastName"].ToString() + " ";
                   record += rdr["sex"];
                   listBox1.Items.Add(record);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string conStr;
            conStr = "Data Source=va-pc;Initial Catalog=University;Integrated Security=True";
            SqlConnection connect = new SqlConnection(conStr);
            connect.Open();
            if (textBox1.Text != "")
            {
                string stNo = textBox1.Text;
                SqlCommand cmd = new SqlCommand("InOutParameter", connect);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter parm = new SqlParameter("@stNo", stNo);
                parm.Direction = ParameterDirection.Input;
                cmd.Parameters.Add(parm);
                SqlParameter parm2 = new SqlParameter("@stName", SqlDbType.VarChar);
                parm2.Size = 50;
                parm2.Direction = ParameterDirection.Output; // This is important!
                cmd.Parameters.Add(parm2);
                cmd.ExecuteNonQuery();
                string result = cmd.Parameters["@stName"].Value.ToString();
                if (result != "")
                    MessageBox.Show("Name and Family : " + result);
                else
                    MessageBox.Show("Record not found");  
            }
            else
                MessageBox.Show("Enter a student number");
        }
    }
}
