none
Csharp conn string - WinForms a Console aplikace

    Obecná diskuse

  • Prosím, zanechte zde níže uvedený zdrojový kód a nereagujte na toto téma. Je nutné, aby tento obsah zůstal zde a nemůže být přesunut kamkoliv jinam z důvodu omezení připojení do 07.05.2013. Děkuji Vám.

    Console

    PROGRAM.CS - KONZOLE
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace Propojeni_konzole
    {
        class Program
        {
            static void Main(string[] args)
            {
                string server = ConfigurationSettings.AppSettings["server"];
                string database = ConfigurationSettings.AppSettings["database"];
    
                Console.WriteLine("Zadejte jméno uživatele: ");
                string user = Console.ReadLine();
                Console.WriteLine("Zadejte heslo: ");
                string password = Console.ReadLine();
                SQLkody DB = new SQLkody();
                DB.Pripojeni(server,database,user,password);
    
                int volba = 0;
                do
                {
                Console.WriteLine("Vyberte: \n0 = Ukoncit program \n1 = Vlozit sklad \n2 = Vypsat sklady");
                    volba = Convert.ToInt32(Console.ReadLine());
    
                    if (volba == 1) // INSERT
                    {
                        Console.Write("Zadejte nazev skladu: ");
                        string nazev = Console.ReadLine();
                        Console.Write("Zadejte zemi skladu: ");
                        string zeme = Console.ReadLine();
                        Console.Write("Zadejte telefon skladu: ");
                        string telefon = Console.ReadLine();
                        Console.Write("Zadejte email skladu: ");
                        string email = Console.ReadLine();
    
                        DB.InsertSklad(nazev, zeme, telefon, email);
                    }
                    if (volba == 2)
                    {
                        VypisSkladu(DB.SelectAllSklad());
                    }
    
    
                } 
                while (volba != 0);
     
                DB.Odpojeni();
                }
    
            static void VypisSkladu(SqlDataReader reader)
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString() + " | " + reader[1].ToString() + " | " + reader[2].ToString() + " | " + reader[3].ToString() + " | " + reader[4].ToString());
                }
            }
    
    
            }       
        }
    
               /*     if (volba == 2) //INSERT
                    {
                        
                    }
                    if (volba == 3) //UPDATE
                    {
                        Console.Write("Zadejte ID: ");
                        int id = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Zadejte nove prijmeni: ");
                        string prijmeni = Console.ReadLine();
    
                        db.UpdateZak(id, prijmeni);
                    }
                    if (volba == 4) //DELETE
                    {
                        Console.Write("Zadejte ID: ");
                        int id = Convert.ToInt32(Console.ReadLine());
    
                        db.DeleteZak(id);
                    }
                */
    
                
              
    
            
    SQLkody.CS
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace Propojeni_konzole
    {
    
        class SQLkody
        {
    
            SqlConnection connection = null;
    
            public void Pripojeni(string server, string database, string user, string password) // metoda pro připojení do DB !!!nutné vstupní parametry!!!
            {
                
                string connString = @"server=" + server + ";database=" + database + ";UID=" + user + ";password=" + password;
    
                try
                {
                    connection = new SqlConnection(connString);
                    connection.Open();
                    Console.WriteLine("Připojeno!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
    
            public void Odpojeni() // metoda pro odpojení z DB
            {
                try
                {
                    connection.Close();
                    Console.WriteLine("Odpojeno.");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
    
            public void Insert(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
    
                try
                {
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Zaznam vlozen!");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
    
            public void InsertSklad(string nazev, string zeme, string telefon, string email)
            { 
            Insert(@"INSERT INTO WinFormy1N.dbo.SKLAD (NAZEV, ZEME, TELEFON, EMAIL) VALUES ('" + nazev + "', '" + zeme + "', '" + telefon + "', '" + email +"')");
            }
    
            public SqlDataReader Select(string sql) // metoda obecně pro Select
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                return cmd.ExecuteReader();
            }
            public SqlDataReader SelectAllSklad() // select * ze skladu
            {
                return Select("SELECT * FROM dbo.SKLAD");
            }
    
    
    
    
        
        }
    }
    APP.CONFIG
    
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    
      <appSettings>
      <add key="server" value= "JOHNNY-PC"></add>
      <add key="database" value= "WinFormy1N"></add>
      </appSettings>
      
    </configuration>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    
    namespace Prace_s_databazi
    {
        class Program
        {
            static void Main(string[] args)
            {
                Database db = new Database();
                db.Connect();
    
    
                int volba = 0;
                do
                {
                    Console.WriteLine("Vyberte: \n0 = Ukoncit program \n1 = Vybrat zaka \n2 = Vlozit zaka \n3 = Upravit zaka \n4 = Smazat zaka");
                    volba = Convert.ToInt32(Console.ReadLine());
    
                    if (volba == 1) //SELECT
                    {
                        Vypis(db.SelectAllZak());
                    }
                    if (volba == 2) //INSERT
                    {
                        Console.Write("Zadejte jmeno: ");
                        string jmeno = Console.ReadLine();
                        Console.Write("Zadejte prijmeni: ");
                        string prijmeni = Console.ReadLine();
    
                        db.InsertZak(jmeno, prijmeni);
                    }
                    if (volba == 3) //UPDATE
                    {
                        Console.Write("Zadejte ID: ");
                        int id = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Zadejte nove prijmeni: ");
                        string prijmeni = Console.ReadLine();
    
                        db.UpdateZak(id, prijmeni);
                    }
                    if (volba == 4) //DELETE
                    {
                        Console.Write("Zadejte ID: ");
                        int id = Convert.ToInt32(Console.ReadLine());
    
                        db.DeleteZak(id);
                    }
    
    
                } while (volba != 0);
                
                db.Disconnect();
                
            }
    
            static void Vypis(SqlDataReader reader)
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString() + " | " + reader[1].ToString() + " | " + reader[2].ToString());
                }
                reader.Close();
            }
        } 
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    
    namespace Prace_s_databazi
    {
        class Database
        {
            
            string username = "*****";
            string password = "****";
            string database = ""; //nazevdb
            string server = @""; //servername
            SqlConnection connection = null;
    
            public void Connect()
            {
                string connString = string.Format("server={0};uid={1};password={2};database={3}", server, username, password, database);
                
                try
                {
                    connection = new SqlConnection(connString);
                    connection.Open();
                    Console.WriteLine("Pripojeno");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            public void Disconnect()
            {
                try
                {
                    connection.Close();
                    //Console.WriteLine("Odpojeno");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
    
            public void Insert(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                try
                {
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Zaznam vlozen !");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            public void InsertZak(string jmeno, string prijmeni)
            {
                Insert(string.Format("INSERT INTO ZAK(Jmeno, Prijmeni) VALUES ('{0}','{1}')", jmeno, prijmeni));
            }
            public void InsertUcitel(string jmeno, string prijmeni)
            {
                Insert(string.Format("INSERT INTO UCITEL(Jmeno, Prijmeni) VALUES ('{0}','{1}')", jmeno, prijmeni));
            }
    
            public void Delete(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                try
                {
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Zaznam smazan !");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            public void DeleteZak(int ID)
            {
                Delete(string.Format("DELETE FROM ZAK WHERE ID_Zak = {0}", ID));
            }
            public void DeleteUcitel(int ID)
            {
                Delete(string.Format("DELETE FROM UCITEL WHERE ID_Ucitel = {0}", ID));
            }
    
            public void Update(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                try
                {
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Zaznam upraven !");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            public void UpdateZak(int ID, string prijmeni)
            {
                Update(string.Format("UPDATE ZAK SET Prijmeni = '{0}' WHERE ID_Zak = {1}", prijmeni, ID));
            }
            public void UpdateUcitel(int ID, string prijmeni)
            {
                Update(string.Format("UPDATE UCITEL SET Prijmeni = '{0}' WHERE ID_Ucitel = {1}", prijmeni, ID));
            }
    
            public SqlDataReader Select(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                return cmd.ExecuteReader();
            }
            public SqlDataReader SelectAllZak()
            {
                return Select("SELECT * FROM ZAK");
            }
            public SqlDataReader SelectAllUcitel()
            {
                return Select("SELECT * FROM UCITEL");
            }
    
    
        }
    }


    ------------------------------------------------

    WindowsForms

    LOGIN.FORM
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using System.Configuration;
    
    namespace WinFormy1N
    {
        public partial class Login : Form
        {
            public Login()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string connectionString = "Data Source=" + textBox3.Text +
                                          ";Initial Catalog=" + textBox4.Text +
                                          ";User ID=" + textBox1.Text +
                                          ";Password=" + textBox2.Text + "";
    
             /*   List<string[]> cstringy = new List<string[]>();
                for (int i = 0; i < ConfigurationSettings.AppSettings.Keys.Count; i++)
                {
                    cstringy.Add(ConfigurationSettings.AppSettings.GetValues(i));
                }
    
                for (int i = 0; i < ConfigurationSettings.AppSettings.Keys.Count; i++)
                {
                    string[] xy = cstringy.ElementAt(i);
    
                    if (xy[0] == connectionString)
                    {
                        Properties.Settings.Default.connectionString = connectionString;
                        Properties.Settings.Default.Save();
                */
                        MessageBox.Show("Připojení ověřeno a povoleno");
    
                        Menu menu = new Menu();
                        menu.Show();
                        this.Hide();
                        return;
                    }
    
            private void Login_Load(object sender, EventArgs e)
            {
    
            }
                //    MessageBox.Show("Přihlášení nebylo povoleno - špatně zadanéh údaje");
                }
                
                
                /*   string username = textBox1.Text;
                string password = textBox2.Text;
                if (SQLkody.Login(username, password) == true)
                {
                    Menu menu = new Menu();
                    menu.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show("Nejde to! :( ");
                   /* Exception q = new Exception();
                    string qq = Convert.ToString(q);
                    MessageBox.Show(qq);*/
    
            }
    
      /*      private void Login_Load(object sender, EventArgs e)
            {
    
            }*/
        
    MENU.FORM
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WinFormy1N
    {
        public partial class Menu : Form
        {
            public Menu()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Zbrane zbran = new Zbrane(); 
                zbran.Show();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                Sklady sklad = new Sklady();
                sklad.Show();
            }
    
            private void Menu_Load(object sender, EventArgs e)
            {
    
            }
    
        }
    }
    ZBRANE.FORM
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
    namespace WinFormy1N
    {
        public partial class Zbrane : Form
        {
            string connectionString = Properties.Settings.Default.connectionString;
            SQLkody db;
    
            public Zbrane()
            {
                InitializeComponent();
                db = new SQLkody(connectionString);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                SqlConnection sqlConn = new SqlConnection(connectionString);
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.ZBRAN;", sqlConn);
                DataTable t = new DataTable();
                da.Fill(t);
                dataGridView1.DataSource = t;
            }
    
            private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
                string atribut = dataGridView1.CurrentCell.OwningColumn.Name;
                string novyZapis = dataGridView1.CurrentCell.Value.ToString();
                int id_zbran = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
                db.UpdateZbran(atribut, novyZapis, id_zbran);
            }
    
            private void Zbrane_Load(object sender, EventArgs e)
            {
                SqlConnection sqlConn = new SqlConnection(connectionString);
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.ZBRAN;", sqlConn);
                DataTable t = new DataTable();
                da.Fill(t);
                dataGridView1.DataSource = t; 
            }
    
         /*   private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                int idCol = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
    
                db.DeleteZbran(idCol);
            }*/
    
            private void button2_Click(object sender, EventArgs e)
            {
                AddZbran addZ = new AddZbran();
                addZ.Show();
            }
    
            private void dataGridView1_UserDeletingRow_1(object sender, DataGridViewRowCancelEventArgs e)
            {
                int id_zbran = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
                db.DeleteZbran(id_zbran);
            }
    
        }
    }

    ADDZBRAN.FORM using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WinFormy1N { public partial class AddZbran : Form { string connectionString = Properties.Settings.Default.connectionString; int id_sklad = 0; SQLkody db1; public AddZbran() { db1 = new SQLkody(connectionString); InitializeComponent(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { id_sklad = int.Parse(comboBox1.SelectedItem.ToString().Substring(0, 1)); } private void comboBox1_Click_1(object sender, EventArgs e) { comboBox1.Items.Clear(); SqlConnection sqlConn = new SqlConnection(connectionString); sqlConn.Open(); SqlCommand cmd = new SqlCommand("SELECT ID_SKLAD, NAZEV FROM dbo.SKLAD;", sqlConn); SqlDataReader srdr = cmd.ExecuteReader(); try { while (srdr.Read() != null) { comboBox1.Items.Add(srdr.GetValue(0) + " " + srdr.GetValue(1)); } } catch (Exception ex) { srdr.Close(); } sqlConn.Close(); } private void button1_Click(object sender, EventArgs e) { string text = comboBox1.Text; string pom = ""; for (int i = 0; i < text.Length; i++) { if (text[i] == ' ') { break; } pom += text[i]; } db1.InsertZbran(int.Parse(pom), textBox1.Text, int.Parse(textBox2.Text), textBox3.Text); // int.Parse(comboBox1.SelectedItem.ToString().Substring(0, 1))); MessageBox.Show("Úspěšně přidáno!"); this.Close(); } private void AddZbran_Load(object sender, EventArgs e) { } } }

    SQLkody.CS
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.Sql;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using System.Configuration;
    using System.Windows.Forms;
    
    namespace WinFormy1N
    {
        class SQLkody
        {
            string key = "";
            SqlConnection sqlconn;
    
            public SQLkody(string key)
            {
                this.key = key;
                sqlconn = new SqlConnection(key);        
    
            }
    
            public void Pripojeni()
            {
                sqlconn.Open();
            }
            public void KonecPripojeni()
            {
                sqlconn.Close();
            }
    
            public void InsertZbran(int id_sklad, string nazev, int vaha, string zemepuvodu)// ,int id_sklad)
            {
                try
                {
                    Pripojeni();
                    SqlCommand cmd = new SqlCommand("INSERT INTO dbo.ZBRAN (ID_SKLAD,NAZEV,VAHA,ZEME_PUVODU) VALUES ('" + id_sklad + "','" + nazev + "','" + vaha + "','" + zemepuvodu +"');", sqlconn); //,'" + id_sklad + "');", sqlconn);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    KonecPripojeni();
                }
    
            }
            public void DeleteZbran(int id_zbran)
            {
                try
                {
                    Pripojeni();
                    SqlCommand cmd = new SqlCommand("DELETE FROM dbo.ZBRAN WHERE ID_ZBRAN=" + id_zbran + ";", sqlconn);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    KonecPripojeni();
                }
            }
    
            public void UpdateZbran(string atribut, string novyVstup, int id_zbran)
            {
    
                Pripojeni();
                SqlCommand cmd = new SqlCommand("UPDATE dbo.ZBRAN SET " + atribut + "='" + novyVstup + "' WHERE ID_ZBRAN=" + id_zbran + ";", sqlconn);
                cmd.ExecuteNonQuery();
                KonecPripojeni();
            }
    
            public void InsertSklad(string nazev, string zeme, string telefon, string email)// ,int id_sklad)
            {
                try
                {
                    Pripojeni();
                    SqlCommand cmd = new SqlCommand("INSERT INTO dbo.SKLAD (NAZEV,ZEME,TELEFON,EMAIL) VALUES ('" + nazev + "','" + zeme + "','" + telefon + "','" + email + "');", sqlconn); //,'" + id_sklad + "');", sqlconn);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    KonecPripojeni();
                }
    
            }
    
            public void DeleteSklad(int id_sklad)
            {
                try
                {
                    Pripojeni();
                    SqlCommand cmd = new SqlCommand("DELETE FROM dbo.SKLAD WHERE ID_SKLAD=" + id_sklad + ";", sqlconn);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    KonecPripojeni();
                }
            }
    
    
            public void UpdateSklad(string novyVstup, string nazev, int id_sklad)  // string nazev, string zeme, string telefon, string email
            {
    
                Pripojeni();
                SqlCommand cmd = new SqlCommand("UPDATE dbo.ZBRAN SET " + nazev + "='" + novyVstup + "' WHERE ID_ZBRAN=" + id_sklad + ";", sqlconn);
                cmd.ExecuteNonQuery();
                KonecPripojeni();
            }
    
            
    
    
    
        /*    public static bool Login(string username, string password)
            {
                SqlConnection conn = null;
                string server = ConfigurationSettings.AppSettings["server"];
                string database = ConfigurationSettings.AppSettings["database"];
                string connString = @"server="+server+";database="+database+";UID="+username+";password="+password+"";
                 conn = new SqlConnection(connString);
    
                try
                {
                    conn.Open();
                    return true;
                }
                catch 
                {
                    return false;
    
                }
            }
         */ 
        
        }
    }
    APP.CONFIG
    
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="WinFormy1N.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
      </configSections>
      <appSettings>
        <add key="connStr" value="Data Source=JOHNNY-PC;Initial Catalog=WinFormy1N;User ID=palaja;Password=123"/>
        <add key="connStr1" value="Data Source=JOHNNY-PC;Initial Catalog=WinFormy1N;User ID=palaja_obyc_user;Password=123"/>
      </appSettings>
      <userSettings>
        <WinFormy1N.Properties.Settings>
          <setting name="connectionString" serializeAs="String">
            <value />
          </setting>
        </WinFormy1N.Properties.Settings>
      </userSettings>
    </configuration>

    ZBRANE.FORM_nove

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
    namespace WinFormy1N
    {
        public partial class Zbrane : Form
        {
            string connectionString = Properties.Settings.Default.connectionString;
            SQLkody db;
    
            public Zbrane()
            {
                InitializeComponent();
                db = new SQLkody(connectionString);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                SqlConnection sqlConn = new SqlConnection(connectionString);
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.ZBRAN;", sqlConn);
                DataTable t = new DataTable();
                da.Fill(t);
                dataGridView1.DataSource = t;
            }
    
            private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
                string atribut = dataGridView1.CurrentCell.OwningColumn.Name;
                string novyZapis = dataGridView1.CurrentCell.Value.ToString();
                int id_zbran = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
              //  db.UpdateZbran(atribut, novyZapis, id_zbran);
            }
    
            private void Zbrane_Load(object sender, EventArgs e)
            {
                SqlConnection sqlConn = new SqlConnection(connectionString);
                sqlConn.Open();
                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.ZBRAN;", sqlConn);
                DataTable t = new DataTable();
                da.Fill(t);
                dataGridView1.DataSource = t; 
            }
    
         /*   private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
            {
                int idCol = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
    
                db.DeleteZbran(idCol);
            }*/
    
            private void button2_Click(object sender, EventArgs e)
            {
                AddZbran addZ = new AddZbran();
                addZ.Show();
            }
    
            private void dataGridView1_UserDeletingRow_1(object sender, DataGridViewRowCancelEventArgs e)
            {
                int id_zbran = int.Parse(dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString());
                db.DeleteZbran(id_zbran);
            }
    
            private void button3_Click(object sender, EventArgs e)
            {
                UpdateZbran upZ = new UpdateZbran();
                upZ.Show();
            }
    
            private void button4_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    
        }
    }
    UPDATEZBRAN.FORM
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.Sql;
    using System.Data.SqlClient;
    
    namespace WinFormy1N
    {
        public partial class UpdateZbran : Form
        {
            string connectionString = Properties.Settings.Default.connectionString;
            SQLkody db1;
    
            public UpdateZbran()
            {
                db1 = new SQLkody(connectionString);
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                db1.UpdateZbran(textBox2.Text, int.Parse(textBox1.Text)); // int.Parse(comboBox1.SelectedItem.ToString().Substring(0, 1))); 
                MessageBox.Show("Úspěšný update");
                this.Close();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                this.Close();
            }
    
            private void UpdateZbran_Load(object sender, EventArgs e)
            {
    
            }
        }
    }

    CONSOLE C#
    PROGRAM.CS (MAIN)
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data; // NUTNÉ
    using System.Data.SqlClient; // NUTNÉ
    using System.Configuration; // NUTNÉ
    
    namespace maturitaConsole1N
    {
        class Program
        {
            static void Main(string[] args)
            {
    
    
                SQL DATABAZE = new SQL(); // NUTNÉ
    
    
                string server = ConfigurationSettings.AppSettings["server"]; // načtení serveru do proměnné server -> z AppConfigu
                string database = ConfigurationSettings.AppSettings["database"];  // načtení databáze do proměnné database -> z AppConfigu
    
                Console.WriteLine("---PRIPOJENI DO DATABAZE---");
                Console.WriteLine("Zadejte vase prihlasovaci jmeno: ");
                string jmeno = Console.ReadLine();
                Console.WriteLine("Zadejte vase heslo: ");
                string heslo = Console.ReadLine();
    
                DATABAZE.Pripojeni(server, database, jmeno, heslo); // použití metody Pripojeni pro objekt naší Databáze
    
                Console.WriteLine("Vítejte v DATABAZI zbraní a skladů!!");
    
                #region DO WHILE - MENU
                int volba = 0;
    
                  do  // konej
                {
                    Console.WriteLine("Vyberte: \n 0 -> odpojit se od databáze \n 1 -> vložit sklad \n 2 -> vypsat všechny sklady \n 3 -> smazat vybraný sklad \n");
                    volba = Convert.ToInt32(Console.ReadLine());
    
                    if (volba == 1)
                    {
                        Console.WriteLine("---PRIDANI SKLADU---");
                        Console.Write("Zadej nazev skladu: ");
                        string nazev = Console.ReadLine();
                        Console.Write("Zadej zemi, kde se sklad nachází: ");
                        string zeme = Console.ReadLine();
                        Console.Write("Zadej telefon do skladu: ");
                        string telefon = Console.ReadLine();
                        Console.Write("Zadej email skladu: ");
                        string email = Console.ReadLine();
    
                        DATABAZE.InsertSklad(nazev, zeme, telefon, email);
                    }
                    if (volba == 2)
                    {
                        Console.WriteLine("---VYPIS SKLADŮ---");
                        VypisSklad(DATABAZE.SelectSklad());
                    }
                    if (volba == 3)
                    {
                        Console.WriteLine("---SMAZÁNÍ SKLADU---");
                        Console.WriteLine("Zadejte ID skladu který chcete smazat.");
                        int id = Convert.ToInt32(Console.ReadLine());
                        DATABAZE.DeleteSklad(id);
                    }
    
                }
                while (volba != 0);  // dokud nebude volba 0
    
                DATABAZE.Odpojeni();
            }
            #endregion DO WHILE - MENU
    
    
            #region METODA PRO VYPIS
            static void VypisSklad(SqlDataReader reader) // SqlDataReader  -> nutný pro selectění celé tabulky
            {
                while (reader.Read()) // dokud se bude mít co číst, bude číst
                {
                    Console.WriteLine(reader[0].ToString() + " | " + reader[1].ToString() + " | " + reader[2].ToString() + " | " + reader[3].ToString() + " | " + reader[4].ToString()); // oddělení záznamů
                }
                reader.Close(); // zavření readeru pro další použití
    
            }
            #endregion METODA PRO VYPIS
    
    
    
        }
    }

    SQL.CS
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data; // NUTNÉ
    using System.Data.SqlClient; // NUTNÉ
    using System.Configuration; // NUTNÉ
    
    namespace maturitaConsole1N
    {
        class SQL
        {
    
            SqlConnection connection = null; // NUTNÉ - prvotní nastavení na nepřipojeno
    
    
            #region METODA PRIPOJENI + CONNECTIONSTRING
            public void Pripojeni(string server, string database, string jmeno, string heslo)
            {
                string connectionString = @"server=" + server + ";database=" + database + ";UID=" + jmeno + ";password=" + heslo;
    
                try
                {
                    connection = new SqlConnection(connectionString);
                    connection.Open();
                    Console.WriteLine("Pripojeno do databaze!");
                }
    
                catch(Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine("NEPRIPOJENO!");
                }
    
            }
            #endregion METODA PRIPOJENI + CONNECTIONSTRING
    
    
            #region METODA ODPOJENI
            public void Odpojeni()
            {
                try 
                {
                    connection.Close();
                    Console.WriteLine("Odpojeno.");
                }
                catch(Exception e)
                {
                    Console.WriteLine(e);
                    Console.WriteLine("Odpojeno");
                }
                
            }
            #endregion METODA ODPOJENI
    
    
            #region INSERT
            public void Insert(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
    
                try
                {
                    cmd.ExecuteNonQuery();
                    Console.WriteLine("Záznam úspěšně vložen!");
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.Message);
                }
    
            }
    
            public void InsertSklad(string nazev, string zeme, string telefon, string email)
            {
                Insert(@"INSERT INTO WinFormy1N.dbo.SKLAD (NAZEV, ZEME, TELEFON, EMAIL) VALUES ('" + nazev + "', '" + zeme + "', '" + telefon + "', '" + email + "')");
            }
            #endregion INSERT
    
    
            #region SELECT
            public SqlDataReader Select(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                return cmd.ExecuteReader();
            }
    
            public SqlDataReader SelectSklad()
            {
                return Select("SELECT * FROM dbo.SKLAD");
            }
    
            #endregion SELECT
    
    
            #region DELETE
            public void Delete(string sql)
            {
    
                SqlCommand cmd = new SqlCommand(sql, connection); // !!!!!!!!!!!!!!!
    
                try
                {
                    cmd.ExecuteNonQuery();   // !!!!!!!!!!!!!!!!
                    Console.WriteLine("Záznam smazán!");
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            
            public void DeleteSklad(int ID)
            {
                Delete("DELETE FROM dbo.SKLAD WHERE ID_SKLAD = " + ID);
            }
            #endregion DELETE
    
    
        }
    }

    WINFORMS->  LOGIN.CS
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace DSwinformy1N
    {
        public partial class Login : Form
        {
            string server;
            string database;
    
            public Login()
            {
                InitializeComponent();
    
                server = ConfigurationSettings.AppSettings["server"];
                database = ConfigurationSettings.AppSettings["database"];
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                if (SQL.instance.Pripojeni(server, database, textBox1.Text, textBox2.Text))
                {
                    Menu menu = new Menu();
                    menu.ShowDialog();
                }
    
            }
    
    
        }
    }
    

    SQL.CS (class)
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Windows.Forms;
    
    
    namespace DSwinformy1N
    {
        class SQL
        {
            static SQL DATABAZE; // název objektu
    
            public static SQL instance
        {
           get
           {
               if (DATABAZE == null)
                DATABAZE = new SQL();
                return DATABAZE;
            }
        }
    
    
            SqlConnection connection = null;
    
            public bool Pripojeni(string server, string database, string username, string password)
            {
                try 
                {
                    connection = new SqlConnection(string.Format(@"server=" + server + ";database=" + database + ";UID=" + username + ";password=" + password));
                    connection.Open();
                    MessageBox.Show("Připojeno.");
                    return true;
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }
    
            public void Odpojeni()
            {
                try
                {
                    connection.Close();
                    MessageBox.Show("Odpojeno.");
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
    
    
    
            public void Insert(string sql)
            {
                SqlCommand cmd = new SqlCommand(sql, connection);
                try
                {
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Záznam vložen.");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
    
    
            public void InsertSklad(string nazev, string zeme, string telefon, string email)
            {
                Insert("INSERT INTO WinFormy1N.dbo.SKLAD (NAZEV,ZEME,TELEFON,EMAIL) VALUES ('" + nazev + "', '" + zeme + "', '" + telefon + "', '" + email + "')");
            }
    
    
            public SqlDataReader Select(string sql)
            {
                try
                {
                    SqlCommand cmd = new SqlCommand(sql, connection);
                    return cmd.ExecuteReader();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return null;
                }
            }
    
            public SqlDataReader SelectSklad()
            {
                return Select("SELECT * FROM WinFormy1N.dbo.SKLAD");
            }
    
    
    
    
        }
    }
    

    MENU.CS
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace DSwinformy1N
    {
        public partial class Menu : Form
        {
            public Menu()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Sklad sklad = new Sklad();
                sklad.Show();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                Zbran zbran = new Zbran();
                zbran.Show();
            }
    
            private void button3_Click(object sender, EventArgs e)
            {
                Vypis(SQL.instance.SelectSklad());
            }
    
            public void Vypis(SqlDataReader reader)
            {
                VypisSklad vypis = new VypisSklad(reader);
                vypis.Show();
            }
    
            private void Menu_Load(object sender, EventArgs e)
            {
    
            }
    
    
        }
    }
    

    SKLAD.CS
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace DSwinformy1N
    {
        public partial class Sklad : Form
        {
            public Sklad()
            {
                InitializeComponent();
            }
    
    
            private void Sklad_Load(object sender, EventArgs e)
            {
    
            }
    
    
            private void button1_Click(object sender, EventArgs e)
            {
                SQL.instance.InsertSklad(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
            }
    
        }
    }
    

    VYPISSKLAD.CS
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Configuration;
    
    namespace DSwinformy1N
    {
        public partial class VypisSklad : Form
        {
            SqlDataReader reader;
    
    
            public VypisSklad(SqlDataReader reader)
            {
                InitializeComponent();
    
                this.reader = reader;
            }
    
            private void VypisSklad_Load(object sender, EventArgs e)
            {
                DataTable datatable = new DataTable();
                datatable.Load(reader);
                dataGridView1.DataSource = datatable;
    
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                this.Refresh();
            }
        }
    }
    








    17. dubna 2013 21:47

Všechny reakce