Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: _vicho_ en 16 Octubre 2019, 18:32 pm



Título: Aasignar eventos a Controles creados en tiempo de ejecucion
Publicado por: _vicho_ en 16 Octubre 2019, 18:32 pm
Hola buen día a todos, me encuentro realizando un cotizador en C# y SQL, decidí crear los controles segun los articulos que se le pueden o no agregar al modelo final, separe cada componente en un grupbox y si llega a tener varias opciones agrege un radio button para que el cliente seleccione el articulo que mas le convenga en su cotizacion, ya me dibuja el formulario tal cual el problema  :laugh: es como agrego el precio a el total si no puedo definir los eventos en cada radio button, tengo 2 dias leyendo si existe alguna instancia o algo donde le defina el precio de cada articulo pero no e tenido suerte.

este es el codigo que estoy usando:

                int y = 100;
                int y2 = 1;
                foreach (DataRow row in dt.Rows)
                {
                    GroupBox grupo = new GroupBox();
                    grupo.Text = row[0].ToString();
                    grupo.Size = new System.Drawing.Size(1150, 100);
                    grupo.Location = new System.Drawing.Point(10, y);
                    this.Controls.Add(grupo);

                    string comparar = row[1].ToString();
                    if (comparar == "1")
                    {
                        using (SqlConnection con = new SqlConnection(datosConexion))
                        {
                            con.Open();
                            string textoCmd2 = "SELECT Articulo FROM [Norte].[dbo].[Componentes] where Nombre = '" + row[0].ToString() + "'";
                            SqlCommand cmd2 = new SqlCommand(textoCmd2, con);
                            cmd2.ExecuteNonQuery();
                            con.Close();
                            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
                            da2.Fill(dt2);
                        }
                        foreach (DataRow row2 in dt2.Rows)
                        {

                            RadioButton btn = new RadioButton();
                            btn.Text = row2[0].ToString();
                            btn.Size = new System.Drawing.Size(130, 40);
                            btn.Location = new System.Drawing.Point(y2, 40);
                            grupo.Controls.Add(btn);
                            y2 = y2 + 135;
                            ToolTip buttonToolTip = new ToolTip();
                            buttonToolTip.SetToolTip(btn, btn.Name.ToString());
                        }
                        
                        dt2.Clear();
                        y2 = 1;
                    }
                    else
                    {
                        RadioButton btn = new RadioButton();
                        btn.Text = row[0].ToString();
                        btn.Size = new System.Drawing.Size(120, 40);
                        btn.Location = new System.Drawing.Point(1, 40);
                        grupo.Controls.Add(btn);
                    }
                    y = y + 100;
                }
            }
            catch
            {
                MessageBox.Show("No hay conexion", "No se puede descargar la informacion del servidor ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

Gracias por responder, hasta ponto. ::)


Título: Re: Aasignar eventos a Controles creados en tiempo de ejecucion
Publicado por: Serapis en 16 Octubre 2019, 22:05 pm
En tiempo de diseño ya debes tener definido el evento (lo que tenga que hacer)... simplemente crea la función que actúa como evento y que reciba los parámetros que recibiría si lo definieras sobre el tipo de control que creas dinámicamente.

Luego al momento de crear el control, lo enganchas al controlador (AddHandler... ) de eventos que creaste durante diseño...


Título: Re: Aasignar eventos a Controles creados en tiempo de ejecucion
Publicado por: Eleкtro en 17 Octubre 2019, 19:42 pm
Sencillamente debes utilizar el operador += (el equivalente al método AddHandler que mencionó NEBIRE) ...

  • + and += operators (C# reference) | Microsoft Docs (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/addition-operator)

  • How to: Subscribe to and Unsubscribe from Events (C# Programming Guide) (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-subscribe-to-and-unsubscribe-from-events)


Título: Re: Aasignar eventos a Controles creados en tiempo de ejecucion
Publicado por: _vicho_ en 31 Octubre 2019, 16:26 pm
Muchas Gracias (NEBIRE, Eleкtro) me dieron buena direccion, dejo el codigo por si alguien mas busca este tema:

Código
  1.        public Recetas()
  2.        {
  3.            InitializeComponent();
  4.            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
  5.        }
  6.  
  7.        private void Recetas_Load(object sender, EventArgs e)
  8.        {
  9.            cargador();
  10.        }
  11.  
  12.        public void cargador()
  13.        {
  14.            DataTable dt2 = new DataTable();
  15.            try
  16.            {
  17.                DataTable dt = new DataTable();
  18.                using (SqlConnection con = new SqlConnection(datosConexion))
  19.                {
  20.                    con.Open();
  21.                    string textoCmd = "SELECT DISTINCT Nombre, Opcion FROM [Norte].[dbo].[Componentes]";
  22.                    SqlCommand cmd = new SqlCommand(textoCmd, con);
  23.                    cmd.ExecuteNonQuery();
  24.                    con.Close();
  25.                    SqlDataAdapter da = new SqlDataAdapter(cmd);
  26.                    da.Fill(dt);
  27.                }
  28.                int y = 100;
  29.                int y2 = 1;
  30.                foreach (DataRow row in dt.Rows)
  31.                {
  32.                    GroupBox grupo = new GroupBox();
  33.                    grupo.Text = row[0].ToString();
  34.                    grupo.Size = new System.Drawing.Size(1150, 100);
  35.                    grupo.Location = new System.Drawing.Point(10, y);
  36.                    MainFLP.Controls.Add(grupo);
  37.  
  38.                    string comparar = row[1].ToString();
  39.                    if (comparar == "1")
  40.                    {
  41.                        using (SqlConnection con = new SqlConnection(datosConexion))
  42.                        {
  43.                            con.Open();
  44.                            string textoCmd2 = "SELECT Articulo FROM [Norte].[dbo].[Componentes] where Nombre = '" + row[0].ToString() + "'";
  45.                            SqlCommand cmd2 = new SqlCommand(textoCmd2, con);
  46.                            cmd2.ExecuteNonQuery();
  47.  
  48.                            con.Close();
  49.                            SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
  50.                            da2.Fill(dt2);
  51.                        }
  52.                        foreach (DataRow row2 in dt2.Rows)
  53.                        {
  54.  
  55.                            RadioButton btn = new RadioButton();
  56.                            btn.Text = row2[0].ToString();
  57.                            btn.Size = new System.Drawing.Size(130, 40);
  58.                            btn.Location = new System.Drawing.Point(y2, 40);
  59.                            grupo.Controls.Add(btn);
  60.                            y2 = y2 + 135;
  61.                            ToolTip buttonToolTip = new ToolTip();
  62.                            buttonToolTip.SetToolTip(btn, btn.Name.ToString());
  63.  
  64.                            btn.CheckedChanged += AsignadorRadios;
  65.  
  66.                        }
  67.  
  68.                        dt2.Clear();
  69.                        y2 = 1;
  70.                    }
  71.                    else
  72.                    {
  73.                        RadioButton btn = new RadioButton();
  74.                        btn.Text = row[0].ToString();
  75.                        btn.Size = new System.Drawing.Size(120, 40);
  76.                        btn.Location = new System.Drawing.Point(1, 40);
  77.                        grupo.Controls.Add(btn);
  78.  
  79.                        btn.CheckedChanged += AsignadorRadios;
  80.                    }
  81.  
  82.                    y = y + 100;
  83.                }
  84.            }
  85.            catch
  86.            {
  87.                MessageBox.Show("No hay conexion", "No se puede descargar la informacion del servidor ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  88.            }
  89.  
  90.        }
  91.  
  92.  
  93.        void AsignadorRadios(object sender, EventArgs e)
  94.        {
  95.            RadioButton ctrl = sender as RadioButton;
  96.  
  97.            if (ctrl.Checked == true)
  98.            {
  99.            using (SqlConnection con = new SqlConnection(datosConexion))
  100.            {
  101.                con.Open();
  102.                string textoCmd = "SELECT Costo FROM [Norte].[dbo].[Componentes] where Articulo = '" + ctrl.Text + "'";
  103.                SqlCommand cmd = new SqlCommand(textoCmd, con);
  104.  
  105.                string textoCmd2 = "SELECT Cantidad FROM [Norte].[dbo].[Componentes] where Articulo = '" + ctrl.Text + "'";
  106.                SqlCommand cmd2 = new SqlCommand(textoCmd2, con);
  107.  
  108.  
  109.                cmd.ExecuteNonQuery();
  110.                    cmd2.ExecuteNonQuery(); try
  111.                    {
  112.                        Costo = cmd.ExecuteScalar().ToString();
  113.                        Cantidad = cmd2.ExecuteScalar().ToString();
  114.                    }
  115.                    catch
  116.                    {
  117.                        using (SqlConnection con3 = new SqlConnection(datosConexion))
  118.                        {
  119.                            con3.Open();
  120.                            string textoCmd3 = "SELECT SUM (Costo * Cantidad) FROM [Norte].[dbo].[Componentes] where Nombre = '" + ctrl.Text + "'";
  121.                            SqlCommand cmd3 = new SqlCommand(textoCmd3, con3);
  122.                            cmd3.ExecuteNonQuery();
  123.  
  124.                            sumatoria = cmd3.ExecuteScalar().ToString();
  125.                            neto = neto + Convert.ToDouble(sumatoria);
  126.  
  127.                        }
  128.                    }
  129.                    con.Close();
  130.  
  131.            }
  132.            Multi = Convert.ToDouble(Costo) * Convert.ToDouble(Cantidad);
  133.            neto = neto + Multi;
  134.            }
  135.            else
  136.            {
  137.  
  138.                using (SqlConnection con = new SqlConnection(datosConexion))
  139.                {
  140.                    con.Open();
  141.                    string textoCmd = "SELECT Costo FROM [Norte].[dbo].[Componentes] where Articulo = '" + ctrl.Text + "'";
  142.                    SqlCommand cmd = new SqlCommand(textoCmd, con);
  143.  
  144.                    string textoCmd2 = "SELECT Cantidad FROM [Norte].[dbo].[Componentes] where Articulo = '" + ctrl.Text + "'";
  145.                    SqlCommand cmd2 = new SqlCommand(textoCmd2, con);
  146.  
  147.  
  148.                    cmd.ExecuteNonQuery();
  149.                    cmd2.ExecuteNonQuery();
  150.                    Costo = cmd.ExecuteScalar().ToString();
  151.                    Cantidad = cmd2.ExecuteScalar().ToString();
  152.  
  153.                    con.Close();
  154.  
  155.                }
  156.                Multi = Convert.ToDouble(Costo) * Convert.ToDouble(Cantidad);
  157.                neto = neto - Multi;
  158.            }
  159.  
  160.            label1.Text = "$" + neto.ToString("N2");
  161.        }
  162.