using System;
using System.Windows.Forms;
//------------------------------------
using System.Data;
using System.Data.SqlClient;

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

        SqlConnection sCon;
        SqlDataAdapter sda;
        DataSet ds;
        SqlCommand sc;

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
            textBox2.Text = string.Empty;
            groupBox1.Enabled = true;
            button1.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            groupBox1.Enabled = false;
            textBox2.RightToLeft = RightToLeft.Yes;
        }

        private void SaveRecord()
        {

            string strConn = "Server=.;" + "DataBase=Shop;" +
                             "Integrated Security=True";

            string strDA = "Select * From Books Where ID = '" +
                            textBox1.Text + "'";

            string strInsert = @"Insert Into Books(ID, Book_Name)
                        Values(@ID, @Book_Name)";

            sCon = new SqlConnection(strConn);
            sda = new SqlDataAdapter(strDA, sCon);
            ds = new DataSet();
            sda.Fill(ds, "table1");

            if (ds.Tables["table1"].Rows.Count == 0)
            {
                sc = new SqlCommand();
                sc.CommandType = CommandType.Text;
                sc.CommandText = strInsert;

                sc.Parameters.AddWithValue("@ID",
                                 Convert.ToInt32(textBox1.Text.Trim()));

                sc.Parameters.AddWithValue("@Book_Name",
                                 textBox2.Text.Trim());

                sc.Connection = sCon;
                sc.Connection.Open();
                sc.ExecuteNonQuery();
                sc.Connection.Close();

                groupBox1.Enabled = false;

                MessageBox.Show("رکورد مورد نظر به بانک اطلاعاتی اضافه شد");
            }
            else
                MessageBox.Show("کد کتاب تکراری است");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveRecord();
            groupBox1.Enabled = false;
            button1.Enabled = true;
        }
    }
}