using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class Grade : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataList1.DataSource = OrigemDados();
            DataList1.DataBind();
            int entrada = 0;
            if (Int32.TryParse(Request.QueryString["Id"], out entrada))
            {
                lblCategoria.Text = " " + LegendaCategoria(entrada) + "<p/>";
            }
        }
    }

    DataView OrigemDados()
    {
        DataView origem = null;
        int entrada;
        if (Request.QueryString["Id"] != null)
        {
            if (!Int32.TryParse(Request.QueryString["Id"], out entrada)) return null;

            ConnectionStringSettings getString = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings;
            if (getString != null)
            {
                string sSql = "SELECT Categories.CategoryID, Products.ProductName, Products.UnitsInStock, Products.UnitPrice " +
            "FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID " +
            "GROUP BY Categories.CategoryID, Products.ProductName, Products.UnitsInStock, Products.UnitPrice " +
            "HAVING Categories.CategoryID=@id";

                using (SqlConnection conn = new SqlConnection(getString.ConnectionString))
                {
                    DataSet ds = new DataSet();
                    SqlParameter param = null;

                    SqlCommand cmd = new SqlCommand(sSql, conn);
                    cmd.CommandType = CommandType.Text;

                    param = cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
                    param.Value = entrada;

                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(ds);
                    origem = new DataView(ds.Tables[0]);
                }
            }
        }
        else
        {
            return null;
        }
        return origem;
    }

    string LegendaCategoria(int i)
    {
        switch (i)
        {
            case 1:
                return "Bebidas";
            case 2:
                return "Condimentos";
            case 3:
                return "Confeitos";
            case 4:
                return "Laticínios";
            case 5:
                return "Grãos/Cereais";
            case 6:
                return "Carnes/Aves";
            case 7:
                return "Hortigranjeiros";
            case 8:
                return "Frutos do Mar";
            default:
                return "Opção inválida";
        }
    }
}


