code asp.net c# oledb, cookies, if else

2019-09-19 13:23发布

问题:

Can somebody help understand this code?

protected void Page_Load(object sender, EventArgs e)
    {
        Database database = new Database();

        OleDbConnection conn = database.connectDatabase();

        if (Request.Cookies["BesteldeArtikelen"] == null)
        {
            lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
        }
        else
        {
            HttpCookie best = Request.Cookies["BesteldeArtikelen"];

            int aantal_bestel = best.Values.AllKeys.Length;
            int[] bestelde = new int[aantal_bestel];
            int index = 0;

            foreach (string art_id in best.Values.AllKeys) 
            {
                int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));

                int artikel_id = int.Parse(art_id); // moet getalletje zijn

                if (aantalbesteld != 0)  
                {
                    bestelde[index] = artikel_id;
                }
                index++;
            }

            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
                String.Join(", ", bestelde) + ")";


            try
            {
                conn.Open();

                OleDbDataReader reader = cmd.ExecuteReader();
                GridView1.DataSource = reader;
                GridView1.DataBind();
            }

            catch (Exception error)
            {
                errorMessage.Text = error.ToString();
            }

            finally
            {
                conn.Close();
            }
        }
    }

And there is this part of code i dont really understand:

public string aantalVoorArtikel(object id)
    {
        int artikel_id = (int)id;

        if (Request.Cookies["BesteldeArtikelen"] != null &&
            Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
        {
            return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
        }
        else
        {
            return "0";
        }
    }

回答1:

It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.