Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

The book who I selected doesn't move to the right in CheckedListBox and the reason is that I can't make an return.his code is good just for first user who I selected

$
0
0

Imprumut = loan

I have 6 tables: 


I have one combobox(from where I select utilizatori(users)) and 2 CheckedListBox(Between first box and second box I have 2 buttons:imprumuta(loan) and restituie(return))

This c# code works just for first user: Utilizator, but something's not good. When I add new utilizator(user) and select it,  the loan will be add in my SQL DataBase, but... the book who I selected doesn't move to the right in CheckedListBox and the reason is that I can't make an return

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 MySql.Data.MySqlClient;

namespace proiect
{
    public partial class Imprumut : Form
    {
        MySqlConnection con = new MySqlConnection("DataSource=localhost;UserID=root;database=biblio1");
        //stabilim conexiunea
        MySqlCommand comUser;//interogarea pe baza careia umplem comboBox
        MySqlDataAdapter adaptu;
        DataTable userT = new DataTable();

        MySqlCommand cmdCarti;//interogarea pe baza careia umplem checkListBox
        MySqlDataAdapter adaptCarti;
        DataTable CartiTabel = new DataTable();

        MySqlCommand cmdCartiImprumutate;//interogarea pe baza careia umplem checkListBox
        MySqlDataAdapter adaptCartiImprumutate;
        DataTable CartiImprumutateTabel = new DataTable();

        public int UserId
        {
            get
            {
                return Convert.ToInt32(user.SelectedValue.ToString());
            }
        }

        void Completez_Combo_User()
        {

            try
            {
                comUser = new MySqlCommand("SELECT n.userid, CONCAT(n.UserName) as UserN FROM users n left join userroles us on n.userid=us.userid left join roles r on r.roleid=us.roleid WHERE r.roleid='3'", con);
                adaptu = new MySqlDataAdapter(comUser);
                adaptu.Fill(userT);
                user.Items.Clear();
                user.DataSource = userT;
                //DataTable din care sunt preluate datele pentru ComboBox user
                user.ValueMember = "UserID";
                //Valoarea din coloana UserID nu se afiseaza in combobox
                user.DisplayMember = "UserN";
                //Eelementele afisate in combobox, preluate din concatenarea mai multor coloane
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void Completez_CheckList_Carti()
        {

            try
            {
                cmdCarti = new MySqlCommand("SELECT BookID, CONCAT(title, ' ', ISBN,' ',author)as date_carte FROM books WHERE NumberLeft > 0 ORDER BY BookID", con);
                adaptCarti = new MySqlDataAdapter(cmdCarti);
                adaptCarti.Fill(CartiTabel);
                imp.Items.Clear();
                //carti.DataSource=null;
                imp.DataSource = CartiTabel;
                //DataTable din care sunt preluate datele pentru ComboBox carte
                imp.ValueMember = "BookID";
                //Valoarea din coloana BookID nu se afiseaza in combobox
                imp.DisplayMember = "date_carte";
                //Eelementele afisate in combobox, preluate din concatenarea mai multor coloane


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

            void Completez_CheckList_Cartires()
            {

                try
                {
                    cmdCartiImprumutate = new MySqlCommand(string.Format("SELECT b.BookID, CONCAT(title, ' ', ISBN,' ',author) as date_carte FROM books b inner join userbooks ub on ub.bookid = b.bookid WHERE ub.userid = {0} ORDER BY BookID", UserId), con);
                    adaptCartiImprumutate = new MySqlDataAdapter(cmdCartiImprumutate);
                    adaptCartiImprumutate.Fill(CartiImprumutateTabel);
                    res.Items.Clear();
                    //carti.DataSource=null;
                    res.DataSource = CartiImprumutateTabel;
                    //DataTable din care sunt preluate datele pentru ComboBox carte
                    res.ValueMember = "BookID";
                    //Valoarea din coloana BookID nu se afiseaza in combobox
                    res.DisplayMember = "date_carte";
                    //Eelementele afisate in combobox, preluate din concatenarea mai multor coloane


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

        void Inregistrez_imprumut_in_BD()

        {
            int useridu = Convert.ToInt32(user.SelectedValue.ToString()); //useridu = id book
            int bookidi;
            try
            {
                DateTime azi = System.DateTime.Now; //  Data imprumutului
                DateTime atunci = termenul.Value;   //  Data restituirii
                MySqlTransaction tranzactie = con.BeginTransaction();
                MySqlCommand adaugImpr = new MySqlCommand("INSERT INTO bookshistory(UserID, BookID,BorrowDate) VALUES(@UserID, @BookID, CAST(@BorrowDate as datetime))", con);
                MySqlCommand scadCarti = new MySqlCommand("UPDATE books SET numberleft=numberleft-1 WHERE bookid=@bookid", con);
                MySqlCommand adauga_userbooks = new MySqlCommand("INSERT INTO userbooks(userId,bookID)VALUES(@userID,@bookID)", con);
                adauga_userbooks.Transaction = tranzactie;
                adaugImpr.Transaction = tranzactie;
                scadCarti.Transaction = tranzactie;

                try
                {
                    foreach (int i in imp.CheckedIndices)
                    {
                        imp.SelectedIndex = i;
                        bookidi = Convert.ToInt32(imp.SelectedValue.ToString());

                        MessageBox.Show(bookidi.ToString());
                                 //bookidi va fi id-ul cartea bifata, pe rand din checklistBox
                                 //Inregistrez in tabela imprumut
                        adaugImpr.Parameters.AddWithValue("@UserID", useridu);
                        adaugImpr.Parameters.AddWithValue("@BookID", bookidi);
                        adaugImpr.Parameters.AddWithValue("@BorrowDate", azi);
                        adaugImpr.ExecuteNonQuery();
                        adaugImpr.Parameters.Clear();

                        adauga_userbooks.Parameters.AddWithValue("@userID", useridu);
                        adauga_userbooks.Parameters.AddWithValue("@bookID", bookidi);
                        adauga_userbooks.ExecuteNonQuery();
                        adauga_userbooks.Parameters.Clear();

                                //Scad numarl de carti disponibile pentru cartea imprumutat
                        scadCarti.Parameters.AddWithValue("@bookid", bookidi);
                        scadCarti.ExecuteNonQuery();
                        scadCarti.Parameters.Clear();
                    }
                    tranzactie.Commit();
                }
                catch (Exception ex)
                {
                    tranzactie.Rollback();
                    string message = ex.Message;
                    if (ex.Message.ToLower().Contains("duplicate entry"))
                        message = "Una dintre carti mai exista deja";
                    MessageBox.Show(message);
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        void Inregistrez_restituire_in_BD()
        {
            int useridu = Convert.ToInt32(user.SelectedValue.ToString()); //useridu = id book
            int bookidi;
            try
            {
                DateTime azi = System.DateTime.Now; //  Data imprumutului
                DateTime atunci = termenul.Value;   //  Data restituirii
                MySqlTransaction tranzactie = con.BeginTransaction();
                MySqlCommand modificIstoric = new MySqlCommand("UPDATE bookshistory SET returndate = @returnDate WHERE userID = @userID AND bookID = @bookID", con);
                MySqlCommand adaugCarti = new MySqlCommand("UPDATE books SET numberleft = numberleft + 1 WHERE bookID = @bookID", con);
                MySqlCommand sterge_userbooks = new MySqlCommand("DELETE  FROM userbooks WHERE userID = @userID AND bookID = @bookID", con);
                sterge_userbooks.Transaction = tranzactie;
                modificIstoric.Transaction = tranzactie;
                adaugCarti.Transaction = tranzactie;

                try
                {
                    foreach (int i in res.CheckedIndices)
                    {
                        res.SelectedIndex = i;
                        bookidi = Convert.ToInt32(res.SelectedValue.ToString());

                        MessageBox.Show(bookidi.ToString());
                        //bookidi va fi id-ul cartea bifata, pe rand din checklistBox
                        //Inregistrez in tabela imprumut
                        modificIstoric.Parameters.AddWithValue("@UserID", useridu);
                        modificIstoric.Parameters.AddWithValue("@BookID", bookidi);
                        modificIstoric.Parameters.AddWithValue("@returnDate", termenul.Value);
                        modificIstoric.ExecuteNonQuery();
                        modificIstoric.Parameters.Clear();

                        sterge_userbooks.Parameters.AddWithValue("@UserID", useridu);
                        sterge_userbooks.Parameters.AddWithValue("@BookID", bookidi);
                        sterge_userbooks.ExecuteNonQuery();
                        sterge_userbooks.Parameters.Clear();

                        //Scad numarl de carti disponibile pentru cartea imprumutat
                        //adaugCarti.Parameters.AddWithValue("@bookid", bookidi);
                        adaugCarti.Parameters.AddWithValue("@bookid", bookidi);
                        adaugCarti.ExecuteNonQuery();
                        adaugCarti.Parameters.Clear();
                    }
                    tranzactie.Commit();
                }
                catch (Exception ex)
                {
                    tranzactie.Rollback();
                    MessageBox.Show(ex.Message);
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        public Imprumut()
        {
            InitializeComponent();
            try
            {
                con.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            Completez_Combo_User();
            Completez_CheckList_Carti();
            Completez_CheckList_Cartires();
            //selecteaza_carti_utilizator();
            //  Initializez termenul din dateTimePicker la data de peste 15 zile fata de data sistemului
            termenul.Value = System.DateTime.Now.AddDays(15);
        }

        private void imprumuta_Click(object sender, EventArgs e)
        {

            Confirmare c = new Confirmare("Confirmati imprumutul?");
            DialogResult dr = c.ShowDialog();

            if (dr == DialogResult.Yes)

                try
                {
                    Inregistrez_imprumut_in_BD();
                    MessageBox.Show("Imprumutul a fost inregistrat");
                    //Dupa inregistrarea imprumutului o parte din carti nu mai sunt disponibile pentru imprumut
                    //Reincarc in CheckList cu Carti noua lista cu carti ramase dupa imprumut
                    //Pentru asta "resetez" datele din dataTable cartiT (sursa pentru carti.DataSource)
                    CartiTabel.Clear();
                    adaptCarti.Fill(CartiTabel);
                    CartiImprumutateTabel.Clear();
                    adaptCartiImprumutate.Fill(CartiImprumutateTabel);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            if (dr == DialogResult.No)
            {
                MessageBox.Show("Imprumutul NU a fost inregistrat");
                imp.ClearSelected();
                //deselecteaza cartea selectat
                foreach (int i in imp.CheckedIndices)
                    imp.SetItemChecked(i, false);
                //debifeaza cartile bifate
            }

            //if (imp.CheckedItems.Count > 0)
            //{
            //    //res.Items.Clear();
            //    foreach (string str in imp.CheckedItems)
            //        res.Items.Add(str);//adauga in partea cealalta, imprumuta
            //    while (imp.CheckedItems.Count > 0)
            //        imp.Items.Remove(imp.CheckedItems[0]);
            //}
        }

        private void restituie_Click(object sender, EventArgs e)
        {
            Confirmare r = new Confirmare("Confirmati restituirea?");
            DialogResult dr = r.ShowDialog();

            if (dr == DialogResult.Yes)

                try
                {
                    Inregistrez_restituire_in_BD();
                    MessageBox.Show("Restituirea a fost inregistrata");
                    //Dupa inregistrarea imprumutului o parte din carti nu mai sunt disponibile pentru imprumut
                    //Reincarc in CheckList cu Carti noua lista cu carti ramase dupa imprumut
                    //Pentru asta "resetez" datele din dataTable cartiT (sursa pentru carti.DataSource)
                    CartiTabel.Clear();
                    adaptCarti.Fill(CartiTabel);
                    CartiImprumutateTabel.Clear();
                    adaptCartiImprumutate.Fill(CartiImprumutateTabel);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            if (dr == DialogResult.No)
            {
                MessageBox.Show("Restituirea NU a fost inregistrata");
                res.ClearSelected();
                //deselecteaza cartea selectat
                foreach (int i in imp.CheckedIndices)
                    res.SetItemChecked(i, false);
                //debifeaza cartile bifate
            }

            if (res.CheckedItems.Count > 0)
            {
                foreach (string str in res.CheckedItems)
                    imp.Items.Add(str);
                while (res.CheckedItems.Count > 0)
                    res.Items.Remove(res.CheckedItems[0]);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            con.Close();
            this.Close();
        }
        //private void selecteaza_carti_utilizator()
        //{
        //    res.Items.Clear();
        //    MySqlCommand selectcart = new MySqlCommand("select title from books,userbooks where userbooks.userid='" + user.SelectedValue.ToString() + "' and userbooks.bookid=books.bookid", con);
        //    MySqlDataReader reader = selectcart.ExecuteReader();
        //    try
        //    {
        //        while(reader.Read())
        //        {
        //            res.Items.Add(reader["title"]);
        //        }
        //    }
        //    catch(Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //    finally
        //    {
        //        reader.Close();
        //    }
        //}
    }
}


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>