Colabora
 

Programando Aplicaciones para Windows y Linux

Mono Framework + MonoDevelop + MySQL

 

Fecha: 03/Mar/2008 (03-03-08)
Autor: José Paz Aliaga - josepazaliaga@hotmail.com

 


Introducción

En ocasiones escuchamos hablar de que podemos desarrollar aplicaciones que trabajen tanto en SO Windows y Linux así que bajo esa premisa desarrolle una aplicación que funcione en SO Windows y Linux (en mi caso uso la distribución Ubuntu).

Debo resaltar que toda la programación ha sido realizada en el SO Linux distribución Ubuntu 8.04 (aun se encuentra en betas pero para este propósito nos sirve)

Configurando nuestro Ubuntu

Lo primero que debemos hacer luego de tener instalado nuestro SO instalar las siguientes herramientas, haciendo uso de la Herramienta llamada Gestor de Paquetes Synaptic que se ubica en el Menu Sistema, Administracion.

- IDE MonoDevelop 0.18

- El paquete: libmono-i18n2.0-cil versión 1.2.6

- Mono Framework 1.2.6, para verificar que este instalado correctamente, abrimos una terminal y en ella ejecutamos el siguiente comando mono -V, esto nos arrojara como resultado la versión del Framework que tenemos instalado.

Una vez que tenemos todo esto instalado lo anterior procedemos a Iniciar el MonoDevelop como apreciamos en la siguiente Imagen;

Una vez que termine de cargar el programa nos dara una interfaz como la siguiente:

Aprovechando la pantalla anterior para crear un nuevo Proyecto damos Click en la opción Start a New Project y el tipo de proyecto a seleccionar será uno de C# y Proyecto Vacio, a este proyecto le pondremos el siguiente nombre: MySQLFC como vemos mas abajo:

Una vez hecho esto nos quedara al lado derecho del Entorno un Explorador de Soluciones, pero solo con nuestro proyecto y vacio a los cuales tendremos que agregar uno a uno los formulario, clases y controles de usuario.

A continuación agregamos las siguientes clases para poder trabajar y manipularlos, eso lo haremos dando click derecho en el elemento MySQLFC, Añadir, Elemento Nuevo y en pantalla que nos mostrara seleccionamos GENERAL y el tipo Clase Vacia, de esta manera agregamos uno a uno los siguientes elementos.

- clsHelper

- Form1

- navvar

- Program

A todo esto el Explorador de Soluciones debe quedar de la siguiente manera:

Ahora tenemos que agregar las Referencias que usaremos, ya que este IDE a pesar de ser muy bueno aun no posee la capacidad de Diseñar Formularios Windows (Pero si usamos las librerías GTK# si contamos con esa herramienta), según leo esta capacidad vendrá incorporada en próximas versiones de este IDE, para agregar las referencia hacemos Click derecho en el elemento Referencias (que esta situado debajo de MySQLFC) del Explorador de Soluciones, Opcion Editar Referencias en la cual nos saldrá una ventana como la que vemos mas abajo:

En dicha ventana debemos seleccionar los siguientes Elementos que vemos en la imagen de abajo y así es como debería quedar nuestra lista de referencias:

La Referencia MySQL.Data.dll, la pueden bajar de la Pagina Oficial de MySQL y proceder a descomprimir y buscar la DLL en cuestión.

Bien, hasta este punto tendríamos todo listo para empezar a diseñar nuestra pequeña aplicación.

Comenzando a Programar...

Como ya les comente es realmente un "problema" que no tengamos el Diseñador integrado en este IDE, pero eso no es ningún problema ya que según lso conocimientos de .Net que tenemos no nos debería parecer difícil, hacer todo a mano.

Programando la CLASE clsHeper

La siguiente clase me provee funcionalidad tales como enlazar DataGrids con Dataset, ejecutar consultas y cosas similares, no lo explico por que no es el propósito del articulo, además creo que es fácil entenderlo.

using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace MySQLFC
{
    class clsHelper
    {
          private MySqlConnection mycnx = new MySqlConnection("Server=192.168.1.33;
        Port=3306;Database=facturacion;Uid=datos;Pwd=123;");
        public string dni, nombres, direccion;

        public void ejecutarprocedimiento(string nombreprocedimiento, Array parametros )
        {
            mycnx.Open();
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(parametros);
            cmd.CommandText = nombreprocedimiento;
            cmd.Connection = mycnx;
            cmd.ExecuteNonQuery();
            mycnx.Close();
        }

        public DataSet BUSCAR_DATA(string tabla, string columna, string valor)
        {
            try
            {
                string mysqlstr;
                mysqlstr = "SELECT * FROM " + tabla + " WHERE " + columna + " LIKE '" + valor + "%'";
                MySqlDataAdapter da = new MySqlDataAdapter(mysqlstr, mycnx);
                DataSet DS = new DataSet();
                da.Fill(DS, tabla);
                //MessageBox.Show(mysqlstr);
                return DS;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public DataSet BUSCAR_DATA(string mysqlSTR, string tabla)
        {
            try
            {
                MySqlDataAdapter da = new MySqlDataAdapter(mysqlSTR, mycnx);
                DataSet ds = new DataSet();
                da.Fill(ds, tabla);
                return ds;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void bloquear(bool sw, Control contenedor)
        {        
            foreach(Control obj in contenedor.Controls)
            {
                if( obj is TextBox )
                {
                    ((TextBox)(obj)).ReadOnly = sw;
                }
            }
        }
        public void limpiartxt(Control contenedor)
        {
            foreach (Control obj in contenedor.Controls)
            {
                if (obj is TextBox)
                {
                    ((TextBox)(obj)).Text = "";

                }
            }
        }
        public DataSet enlazadatos(string tabla, string pkey)
        {
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " + tabla, mycnx);
            ds.Clear();
            da.Fill(ds, tabla);
            ds.Tables[tabla].PrimaryKey = new DataColumn[] { ds.Tables[tabla].Columns[pkey] }; 
            return ds;
        }
        public DataSet enlazadatos(string tabla, string mysqlstr, string pkey) {
        DataSet ds = new DataSet();
        MySqlDataAdapter da = new MySqlDataAdapter(mysqlstr, mycnx);
        ds.Clear();
        da.Fill(ds, tabla);
       ds.Tables[tabla].PrimaryKey = new DataColumn[] { ds.Tables[tabla].Columns[pkey] };
        return ds;
    }
        public DataSet enlazadatos_sinPK(string tabla)
        {
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " + tabla, mycnx);
            ds.Clear();
            da.Fill(ds, tabla);
            return ds;
        }
        public static void limpiar_errorp(ErrorProvider er, Control contenedor)
        {
            //object obj;
            foreach (Control obj in contenedor.Controls)
            {
                if (obj is TextBox)
                {
                    er.SetError(((TextBox)(obj)), "");
                }
            }
        }
        public bool valida(ErrorProvider er, Control contenedor)
        {
            bool x = true;
            Control cont;
            cont=contenedor;
            //object obj;
            foreach (Control obj in cont.Controls)
            {
                if (obj is TextBox)
                {        
                    
                    if (((TextBox)(obj)).Text == "")
                    {
                        //MessageBox.Show(((TextBox)(obj)).Name + "Lleno");
                        //er.SetError(((TextBox)(obj)), "Campo Vacio");
                        throw new Exception("Caja de Texto vacia");
                        x = false;
                    }
                    else
                    {
                        //MessageBox.Show(((TextBox)(obj)).Name + "Vacio");
                        //er.SetError(((TextBox)(obj)), "");
                        
                    }
                }
            }
            return x;
        }
        public int indice(DataSet data_set, string tabla, string key, string PriKey)
        {
            Int32 i = 0;
            foreach (DataRow rw in data_set.Tables[tabla].Rows)
            {
                if ((rw[PriKey].ToString() == key.Trim()))
                {
                    break;
                }
                i += 1;
            }
            return i;
        }
    }
}

Programando la Clase Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace MySQLFC
{
    
    public class Form1 : Form
    {
//		ErrorProvider er=new ErrorProvider();	
        private System.ComponentModel.IContainer components = null;
        
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.btnBuscar = new System.Windows.Forms.Button();
            this.btnCancelar = new System.Windows.Forms.Button();
            this.btnGuardar = new System.Windows.Forms.Button();
            this.label6 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.label7 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.btnCancelar_Bus = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            this.txtstock = new System.Windows.Forms.TextBox();
            this.txtMarca = new System.Windows.Forms.TextBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.btnEditar = new System.Windows.Forms.Button();
            this.btnNuevo = new System.Windows.Forms.Button();
            this.txtDescripcion = new System.Windows.Forms.TextBox();
            this.Txtprecio = new System.Windows.Forms.TextBox();
            this.txtMedida = new System.Windows.Forms.TextBox();
            this.txtCodigo = new System.Windows.Forms.TextBox();
            this.txtBusqueda = new System.Windows.Forms.TextBox();
            this.marca = new System.Windows.Forms.RadioButton();
            this.medida = new System.Windows.Forms.RadioButton();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.idart = new System.Windows.Forms.RadioButton();
            this.gp = new System.Windows.Forms.GroupBox();
            this.btnAceptar = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.dataGridView1 = new System.Windows.Forms.DataGrid();
            this.navvar1 = new MySQLFC.navvar();
            this.er = new System.Windows.Forms.ErrorProvider(this.components);
            this.groupBox1.SuspendLayout();
            this.groupBox3.SuspendLayout();
            this.gp.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();

            this.SuspendLayout();
            // 
            // btnBuscar
            // 
            this.btnBuscar.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnBuscar.Location = new System.Drawing.Point(456, 120);
            this.btnBuscar.Name = "btnBuscar";
            this.btnBuscar.Size = new System.Drawing.Size(72, 24);
            this.btnBuscar.TabIndex = 14;
            this.btnBuscar.Text = "&Buscar";
            this.btnBuscar.Click += new System.EventHandler(this.btnBuscar_Click);
            // 
            // btnCancelar
            // 
            this.btnCancelar.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnCancelar.Location = new System.Drawing.Point(384, 120);
            this.btnCancelar.Name = "btnCancelar";
            this.btnCancelar.Size = new System.Drawing.Size(72, 24);
            this.btnCancelar.TabIndex = 16;
            this.btnCancelar.Text = "&Cancelar";
            // 
            // btnGuardar
            // 
            this.btnGuardar.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnGuardar.Location = new System.Drawing.Point(312, 120);
            this.btnGuardar.Name = "btnGuardar";
            this.btnGuardar.Size = new System.Drawing.Size(72, 24);
            this.btnGuardar.TabIndex = 15;
            this.btnGuardar.Text = "&Grabar";
            this.btnGuardar.Click += new System.EventHandler(this.btnGuardar_Click);
            // 
            // label6
            // 
            this.label6.BackColor = System.Drawing.Color.Transparent;
            this.label6.Location = new System.Drawing.Point(176, 88);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(48, 16);
            this.label6.TabIndex = 9;
            this.label6.Text = "Stock :";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label5
            // 
            this.label5.BackColor = System.Drawing.Color.Transparent;
            this.label5.Location = new System.Drawing.Point(8, 88);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(48, 16);
            this.label5.TabIndex = 8;
            this.label5.Text = "Precio :";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(192, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(100, 23);
            this.label1.TabIndex = 22;
            this.label1.Text = "Busqueda :";
            // 
            // label7
            // 
            this.label7.BackColor = System.Drawing.Color.Transparent;
            this.label7.Location = new System.Drawing.Point(312, 16);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(72, 16);
            this.label7.TabIndex = 11;
            this.label7.Text = "Descripción :";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label4
            // 
            this.label4.BackColor = System.Drawing.Color.Transparent;
            this.label4.Location = new System.Drawing.Point(8, 64);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(48, 16);
            this.label4.TabIndex = 7;
            this.label4.Text = "Medida :";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // btnCancelar_Bus
            // 
            this.btnCancelar_Bus.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnCancelar_Bus.Location = new System.Drawing.Point(456, 72);
            this.btnCancelar_Bus.Name = "btnCancelar_Bus";
            this.btnCancelar_Bus.Size = new System.Drawing.Size(72, 24);
            this.btnCancelar_Bus.TabIndex = 24;
            this.btnCancelar_Bus.Text = "&Cancelar";
            this.btnCancelar_Bus.Click += new System.EventHandler(this.btnCancelar_Bus_Click);
            // 
            // label3
            // 
            this.label3.BackColor = System.Drawing.Color.Transparent;
            this.label3.Location = new System.Drawing.Point(8, 40);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(48, 16);
            this.label3.TabIndex = 6;
            this.label3.Text = "Marca :";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // label8
            // 
            this.label8.BackColor = System.Drawing.Color.Transparent;
            this.label8.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular,
                System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label8.Location = new System.Drawing.Point(8, 16);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(48, 16);
            this.label8.TabIndex = 5;
            this.label8.Text = "Codigo :";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // txtstock
            // 
            this.txtstock.Location = new System.Drawing.Point(232, 88);
            this.txtstock.Name = "txtstock";
            this.txtstock.Size = new System.Drawing.Size(64, 20);
            this.txtstock.TabIndex = 4;
            this.txtstock.KeyPress += new 
                System.Windows.Forms.KeyPressEventHandler(this.Txtprecio_KeyPress);
            // 
            // txtMarca
            // 
            this.txtMarca.Location = new System.Drawing.Point(64, 40);
            this.txtMarca.Name = "txtMarca";
            this.txtMarca.Size = new System.Drawing.Size(232, 20);
            this.txtMarca.TabIndex = 1;
            // 
            // groupBox1
            // 
            this.groupBox1.BackColor = System.Drawing.Color.Transparent;
            this.groupBox1.Controls.Add(this.navvar1);
            this.groupBox1.Controls.Add(this.btnBuscar);
            this.groupBox1.Controls.Add(this.btnEditar);
            this.groupBox1.Controls.Add(this.btnNuevo);
            this.groupBox1.Controls.Add(this.btnCancelar);
            this.groupBox1.Controls.Add(this.btnGuardar);
            this.groupBox1.Controls.Add(this.label7);
            this.groupBox1.Controls.Add(this.txtDescripcion);
            this.groupBox1.Controls.Add(this.label6);
            this.groupBox1.Controls.Add(this.label5);
            this.groupBox1.Controls.Add(this.label4);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.label8);
            this.groupBox1.Controls.Add(this.txtstock);
            this.groupBox1.Controls.Add(this.Txtprecio);
            this.groupBox1.Controls.Add(this.txtMedida);
            this.groupBox1.Controls.Add(this.txtMarca);
            this.groupBox1.Controls.Add(this.txtCodigo);
            this.groupBox1.Font = new System.Drawing.Font("Arial", 8.25F);
            this.groupBox1.Location = new System.Drawing.Point(8, 47);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(544, 152);
            this.groupBox1.TabIndex = 23;
            this.groupBox1.TabStop = false;
            this.groupBox1.Tag = "";
            // 
            // btnEditar
            // 
            this.btnEditar.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnEditar.Location = new System.Drawing.Point(384, 120);
            this.btnEditar.Name = "btnEditar";
            this.btnEditar.Size = new System.Drawing.Size(72, 24);
            this.btnEditar.TabIndex = 13;
            this.btnEditar.Text = "&Editar";
            this.btnEditar.Click += new System.EventHandler(this.btnEditar_Click);
            // 
            // btnNuevo
            // 
            this.btnNuevo.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnNuevo.Location = new System.Drawing.Point(312, 120);
            this.btnNuevo.Name = "btnNuevo";
            this.btnNuevo.Size = new System.Drawing.Size(72, 24);
            this.btnNuevo.TabIndex = 12;
            this.btnNuevo.Text = "&Nuevo";
            this.btnNuevo.Click += new System.EventHandler(this.btnNuevo_Click);
            // 
            // txtDescripcion
            // 
            this.txtDescripcion.Location = new System.Drawing.Point(312, 32);
            this.txtDescripcion.MaxLength = 999999999;
            this.txtDescripcion.Multiline = true;
            this.txtDescripcion.Name = "txtDescripcion";
            this.txtDescripcion.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.txtDescripcion.Size = new System.Drawing.Size(216, 72);
            this.txtDescripcion.TabIndex = 10;
            // 
            // Txtprecio
            // 
            this.Txtprecio.Location = new System.Drawing.Point(64, 88);
            this.Txtprecio.Name = "Txtprecio";
            this.Txtprecio.Size = new System.Drawing.Size(104, 20);
            this.Txtprecio.TabIndex = 3;
            this.Txtprecio.KeyPress += new 
                System.Windows.Forms.KeyPressEventHandler(this.Txtprecio_KeyPress);
            // 
            // txtMedida
            // 
            this.txtMedida.Location = new System.Drawing.Point(64, 64);
            this.txtMedida.Name = "txtMedida";
            this.txtMedida.Size = new System.Drawing.Size(232, 20);
            this.txtMedida.TabIndex = 2;
            // 
            // txtCodigo
            // 
            this.txtCodigo.Location = new System.Drawing.Point(64, 16);
            this.txtCodigo.Name = "txtCodigo";
            this.txtCodigo.Size = new System.Drawing.Size(72, 20);
            this.txtCodigo.TabIndex = 0;
            // 
            // txtBusqueda
            // 
            this.txtBusqueda.Location = new System.Drawing.Point(192, 40);
            this.txtBusqueda.Name = "txtBusqueda";
            this.txtBusqueda.Size = new System.Drawing.Size(336, 20);
            this.txtBusqueda.TabIndex = 21;
            this.txtBusqueda.TextChanged += new System.EventHandler(this.txtBusqueda_TextChanged);
            // 
            // marca
            // 
            this.marca.BackColor = System.Drawing.Color.Turquoise;
            this.marca.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.marca.Location = new System.Drawing.Point(16, 56);
            this.marca.Name = "marca";
            this.marca.Size = new System.Drawing.Size(120, 16);
            this.marca.TabIndex = 2;
            this.marca.Text = "Marca";
            this.marca.UseVisualStyleBackColor = false;
            // 
            // medida
            // 
            this.medida.BackColor = System.Drawing.Color.Turquoise;
            this.medida.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.medida.Location = new System.Drawing.Point(16, 40);
            this.medida.Name = "medida";
            this.medida.Size = new System.Drawing.Size(120, 16);
            this.medida.TabIndex = 0;
            this.medida.Text = "Medida del Articulo";
            this.medida.UseVisualStyleBackColor = false;
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.idart);
            this.groupBox3.Controls.Add(this.marca);
            this.groupBox3.Controls.Add(this.medida);
            this.groupBox3.Location = new System.Drawing.Point(16, 16);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(160, 80);
            this.groupBox3.TabIndex = 20;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Opciones de Busqueda";
            // 
            // idart
            // 
            this.idart.BackColor = System.Drawing.Color.Turquoise;
            this.idart.Checked = true;
            this.idart.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.idart.Location = new System.Drawing.Point(16, 24);
            this.idart.Name = "idart";
            this.idart.Size = new System.Drawing.Size(120, 16);
            this.idart.TabIndex = 1;
            this.idart.TabStop = true;
            this.idart.Text = "Codigo del Articulo";
            this.idart.UseVisualStyleBackColor = false;
            // 
            // gp
            // 
            this.gp.BackColor = System.Drawing.Color.Transparent;
            this.gp.Controls.Add(this.dataGridView1);
            this.gp.Controls.Add(this.label1);
            this.gp.Controls.Add(this.btnCancelar_Bus);
            this.gp.Controls.Add(this.groupBox3);
            this.gp.Controls.Add(this.txtBusqueda);
            this.gp.Controls.Add(this.btnAceptar);
            this.gp.Location = new System.Drawing.Point(8, 199);
            this.gp.Name = "gp";
            this.gp.Size = new System.Drawing.Size(544, 248);
            this.gp.TabIndex = 24;
            this.gp.TabStop = false;
            // 
            // btnAceptar
            // 
            this.btnAceptar.Enabled = false;
            this.btnAceptar.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnAceptar.Location = new System.Drawing.Point(384, 72);
            this.btnAceptar.Name = "btnAceptar";
            this.btnAceptar.Size = new System.Drawing.Size(72, 24);
            this.btnAceptar.TabIndex = 23;
            this.btnAceptar.Text = "&Aceptar";
            this.btnAceptar.Click += new System.EventHandler(this.btnAceptar_Click);
            // 
            // label2
            // 
            this.label2.BackColor = System.Drawing.Color.Transparent;
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.label2.Font = new System.Drawing.Font("Brush Script MT", 27.75F, 
                System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(8, 7);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(544, 40);
            this.label2.TabIndex = 22;
            this.label2.Text = "Articulos";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // dataGridView1
            // 
            this.dataGridView1.Location = new System.Drawing.Point(16, 103);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(512, 139);            
            // 
            // navvar1
            // 
            this.navvar1.BackColor = System.Drawing.Color.White;
            this.navvar1.Location = new System.Drawing.Point(64, 120);
            this.navvar1.Name = "navvar1";
            this.navvar1.Size = new System.Drawing.Size(232, 26);
            this.navvar1.TabIndex = 17;
            // 
            // er
            // 
            this.er.ContainerControl = this;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(560, 454);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.gp);
            this.Controls.Add(this.label2);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            this.gp.ResumeLayout(false);
            this.gp.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();

            this.ResumeLayout(false);

        }
        
internal System.Windows.Forms.Button btnBuscar;
        internal System.Windows.Forms.Button btnCancelar;
        internal System.Windows.Forms.Button btnGuardar;
        internal System.Windows.Forms.Label label6;
        internal System.Windows.Forms.Label label5;
        internal System.Windows.Forms.Label label1;
        internal System.Windows.Forms.Label label7;
        internal System.Windows.Forms.Label label4;
        internal System.Windows.Forms.Button btnCancelar_Bus;
        internal System.Windows.Forms.Label label3;
        internal System.Windows.Forms.Label label8;
        internal System.Windows.Forms.TextBox txtstock;
        internal System.Windows.Forms.TextBox txtMarca;
        internal System.Windows.Forms.GroupBox groupBox1;
        internal System.Windows.Forms.Button btnEditar;
        internal System.Windows.Forms.Button btnNuevo;
        internal System.Windows.Forms.TextBox txtDescripcion;
        internal System.Windows.Forms.TextBox Txtprecio;
        internal System.Windows.Forms.TextBox txtMedida;
        internal System.Windows.Forms.TextBox txtCodigo;
        internal System.Windows.Forms.TextBox txtBusqueda;
        internal System.Windows.Forms.RadioButton marca;
        internal System.Windows.Forms.RadioButton medida;
        internal System.Windows.Forms.GroupBox groupBox3;
        internal System.Windows.Forms.RadioButton idart;
        internal System.Windows.Forms.GroupBox gp;
        internal System.Windows.Forms.Button btnAceptar;
        internal System.Windows.Forms.Label label2;
        private navvar navvar1;
        private System.Windows.Forms.DataGrid dataGridView1;
        private System.Windows.Forms.ErrorProvider er;
        
        
        #region " Declaracion de Variables Generales"
            DataSet dsArticulos = new DataSet();
            string condicion;
            clsHelper objHelp = new clsHelper();
        #endregion
        #region "Metodo Propios"
            internal void ActualizaDatos()
            {
                this.txtCodigo.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][0].ToString();
                this.txtDescripcion.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][3].ToString();
                this.txtMarca.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][1].ToString();
                this.txtMedida.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][2].ToString();
                this.Txtprecio.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][4].ToString();
                this.txtstock.Text = dsArticulos.Tables[0].
                    Rows[this.BindingContext[dsArticulos, "Articulos"].Position][5].ToString();
            }
            public void x(System.Object sender, System.EventArgs e)
            {
                ActualizaDatos();
            }
        #endregion

        
        
        public Form1()
        {
            InitializeComponent();
        }
        
        private void Form1_Load(object sender, EventArgs e)
        {
            
            this.ClientSize = new System.Drawing.Size(558, 202);

            dsArticulos = objHelp.enlazadatos("articulos", "ID_ARTICULO");

            this.navvar1.inicio(dsArticulos, "Articulos");
            this.navvar1.btnAnterior.Click += new EventHandler(this.x);
            this.navvar1.btnSiguiente.Click += new EventHandler(this.x);
            this.navvar1.btnPrimero.Click += new EventHandler(this.x);
            this.navvar1.btnUltimo.Click += new EventHandler(this.x);
            ActualizaDatos();
            objHelp.bloquear(true, this.groupBox1);
            ActualizaDatos();
        }

        private void btnNuevo_Click(object sender, EventArgs e)
        {
            btnNuevo.Visible = false;
            btnEditar.Visible =false;
            btnBuscar.Enabled = false;
            condicion = "I";
            objHelp.bloquear(false, this.groupBox1);
            objHelp.limpiartxt(this.groupBox1);
            this.txtCodigo.Focus();
        }

        private void btnEditar_Click(object sender, EventArgs e)
        {
            btnNuevo.Visible = false;
            btnEditar.Visible = false;
            btnBuscar.Enabled = false;
            condicion = "U";
            objHelp.bloquear(false, groupBox1);
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            this.ClientSize = new System.Drawing.Size(558, 456);
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            string key;
            key = dataGridView1[dataGridView1.CurrentRowIndex,0].ToString();
            
            this.BindingContext[dsArticulos, "Articulos"].Position = 
                objHelp.indice(this.dsArticulos, "Articulos", key.Trim(), "ID_ARTICULO");
            ActualizaDatos();
            this.ClientSize = new System.Drawing.Size(558, 202);
            txtBusqueda.Clear();
            btnAceptar.Enabled = false;
            this.dataGridView1.DataSource = null;
        }

        private void txtBusqueda_TextChanged(object sender, EventArgs e)
        {
            if (!(txtBusqueda.Text == ""))
            {
                btnAceptar.Enabled = true;
            }
            DataSet ds = new DataSet();
            string condicion;
            condicion = "";
            if (this.idart.Checked == true)
            {
                condicion = "ID_ARTICULO";
            }
            else if (this.medida.Checked == true)
            {
                condicion = "MODELO";
            }
            else if (this.marca.Checked == true)
            {
                condicion = "PLATAFORMA";
            }
            try
            {
                MessageBox.Show(txtBusqueda.Text.Trim());
                ds = objHelp.BUSCAR_DATA("articulos", condicion, txtBusqueda.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ocurrio el Error: " + ex.Message, 
                    "Aplicacion", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.dataGridView1.DataSource = ds.Tables[0];
        }

        private void btnCancelar_Bus_Click(object sender, EventArgs e)
        {
            this.ClientSize = new System.Drawing.Size(558, 202);
            txtBusqueda.Clear();
            btnAceptar.Enabled = false;
            this.dataGridView1.DataSource = null;
        }

        private void Txtprecio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Char.IsNumber(e.KeyChar)))
            {
                er.SetError(((TextBox)(sender)), "");
            }
            else
            {
                e.Handled = true;
                er.SetError(((TextBox)(sender)), "Solo digite Numeros en este Campo");
            }
        }

        private void btnGuardar_Click(object sender, EventArgs e)
        {
            
                if( objHelp.valida(er, groupBox1) )
                {
                    try
                    {
                        MySqlParameter[] param = new MySql.Data.MySqlClient.MySqlParameter[7];
                        param[0] = new MySqlParameter("?condicion", condicion); 
                        param[1] = new MySqlParameter("?Xidarticulo", txtCodigo.Text); 
                        param[2] = new MySqlParameter("?Xmodelo", txtMarca.Text); 
                        param[3] = new MySqlParameter("?Xplataforma", txtMedida.Text); 
                        param[4] = new MySqlParameter("?Xcaracteristicas", txtDescripcion.Text);
                        param[5] = new MySqlParameter("?Xpre_arti", Txtprecio.Text);
                        param[6] = new MySqlParameter("?Xstock_arti", txtstock.Text);
                        objHelp.ejecutarprocedimiento("MANTE_Articulo", param);
                        MessageBox.Show("Datos registrados Correctamente", "Aplicacion",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnNuevo.Visible = true;
                        btnEditar.Visible = true;
                        btnBuscar.Enabled = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Ocurrio el Error: " + ex.Message, "Aplicacion", 
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        this.dsArticulos = objHelp.enlazadatos("articulos", "ID_ARTICULO");
                        this.navvar1.inicio(this.dsArticulos, "Articulos");
                        objHelp.bloquear(true, groupBox1);
                    }                
                }
                else
                {
                    MessageBox.Show("Verifique los campos en Blanco", "Aplicacion",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                Rectangle rectangulo = new Rectangle(new Point(0, 0), this.ClientSize);
                //System.Drawing.Drawing2D.LinearGradientBrush
                System.Drawing.Drawing2D.LinearGradientBrush linear = new 
                    System.Drawing.Drawing2D.LinearGradientBrush(rectangulo, 
                    System.Drawing.SystemColors.InactiveCaption, Color.White, 
                    System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal);
                e.Graphics.FillRectangle(linear, rectangulo);
            }
            catch (Exception ex)
            {
            }
        }
    }
    
}

Como podemos apreciar estamos diseñando el nuestro formulario vía código y también programando sus eventos, todo esto de forma manual, ahora bueno pues no vayan a pensar que me se todas las propiedades de memoria y todas esas cosas que se necesitan para programar un formulario de forma manual, para hacer esto me guie con el Visual Studio así que hay que guiarnos con el.

Programando el Control de Usuario navvar

bueno recordando hace un tiempo desarrolle con Control de Usuario llamado Barra de Navegacion (si es que la memoria no me falla) bueno aquí es donde lo volví a Implementar

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace MySQLFC
{
    
    
    public class navvar : UserControl
    {
        private System.ComponentModel.IContainer components = null;
        
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        
 private void InitializeComponent()
        {
            this.lblnavegador = new System.Windows.Forms.Label();
            this.btnAnterior = new System.Windows.Forms.Button();
            this.btnSiguiente = new System.Windows.Forms.Button();
            this.panel2 = new System.Windows.Forms.Panel();
            this.btnEliminar = new System.Windows.Forms.Button();
            this.btnPrimero = new System.Windows.Forms.Button();
            this.btnUltimo = new System.Windows.Forms.Button();
            this.panel2.SuspendLayout();
            this.SuspendLayout();
            // 
            // lblnavegador
            // 
            this.lblnavegador.BackColor = System.Drawing.Color.White;
            this.lblnavegador.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lblnavegador.Location = new System.Drawing.Point(80, 0);
            this.lblnavegador.Name = "lblnavegador";
            this.lblnavegador.Size = new System.Drawing.Size(32, 24);
            this.lblnavegador.TabIndex = 21;
            this.lblnavegador.Text = "1";
            this.lblnavegador.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // btnAnterior
            // 
            this.btnAnterior.BackColor = System.Drawing.Color.Transparent;
            this.btnAnterior.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnAnterior.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnAnterior.Location = new System.Drawing.Point(40, 0);
            this.btnAnterior.Name = "btnAnterior";
            this.btnAnterior.Size = new System.Drawing.Size(40, 24);
            this.btnAnterior.TabIndex = 18;
            this.btnAnterior.Text = "<";
            this.btnAnterior.UseVisualStyleBackColor = false;
            this.btnAnterior.Click += new System.EventHandler(this.btnAnterior_Click);
            // 
            // btnSiguiente
            // 
            this.btnSiguiente.BackColor = System.Drawing.Color.Transparent;
            this.btnSiguiente.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnSiguiente.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnSiguiente.Location = new System.Drawing.Point(112, 0);
            this.btnSiguiente.Name = "btnSiguiente";
            this.btnSiguiente.Size = new System.Drawing.Size(40, 24);
            this.btnSiguiente.TabIndex = 19;
            this.btnSiguiente.Text = ">";
            this.btnSiguiente.UseVisualStyleBackColor = false;
            this.btnSiguiente.Click += new System.EventHandler(this.btnSiguiente_Click);
            // 
            // panel2
            // 
            this.panel2.BackColor = System.Drawing.Color.Transparent;
            this.panel2.Controls.Add(this.btnEliminar);
            this.panel2.Controls.Add(this.lblnavegador);
            this.panel2.Controls.Add(this.btnAnterior);
            this.panel2.Controls.Add(this.btnPrimero);
            this.panel2.Controls.Add(this.btnSiguiente);
            this.panel2.Controls.Add(this.btnUltimo);
            this.panel2.Location = new System.Drawing.Point(0, 0);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(232, 24);
            this.panel2.TabIndex = 24;
            // 
            // btnEliminar
            // 
            this.btnEliminar.BackColor = System.Drawing.Color.Transparent;
            this.btnEliminar.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnEliminar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnEliminar.Location = new System.Drawing.Point(192, 0);
            this.btnEliminar.Name = "btnEliminar";
            this.btnEliminar.Size = new System.Drawing.Size(40, 24);
            this.btnEliminar.TabIndex = 22;
            this.btnEliminar.Text = "x";
            this.btnEliminar.UseVisualStyleBackColor = false;
            // 
            // btnPrimero
            // 
            this.btnPrimero.BackColor = System.Drawing.Color.Transparent;
            this.btnPrimero.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnPrimero.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnPrimero.Location = new System.Drawing.Point(0, 0);
            this.btnPrimero.Name = "btnPrimero";
            this.btnPrimero.Size = new System.Drawing.Size(40, 24);
            this.btnPrimero.TabIndex = 17;
            this.btnPrimero.Text = "<<";
            this.btnPrimero.UseVisualStyleBackColor = false;
            this.btnPrimero.Click += new System.EventHandler(this.btnPrimero_Click);
            // 
            // btnUltimo
            // 
            this.btnUltimo.BackColor = System.Drawing.Color.Transparent;
            this.btnUltimo.Cursor = System.Windows.Forms.Cursors.Hand;
            this.btnUltimo.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnUltimo.Location = new System.Drawing.Point(152, 0);
            this.btnUltimo.Name = "btnUltimo";
            this.btnUltimo.Size = new System.Drawing.Size(40, 24);
            this.btnUltimo.TabIndex = 20;
            this.btnUltimo.Text = ">>";
            this.btnUltimo.UseVisualStyleBackColor = false;
            this.btnUltimo.Click += new System.EventHandler(this.btnUltimo_Click);
            // 
            // navvar
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.White;
            this.Controls.Add(this.panel2);
            this.Name = "navvar";
            this.Size = new System.Drawing.Size(232, 24);
            this.panel2.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        internal System.Windows.Forms.Label lblnavegador;
        internal System.Windows.Forms.Button btnAnterior;
        internal System.Windows.Forms.Button btnSiguiente;
        internal System.Windows.Forms.Panel panel2;
        internal System.Windows.Forms.Button btnEliminar;
        internal System.Windows.Forms.Button btnPrimero;
        internal System.Windows.Forms.Button btnUltimo;        
        
        public navvar()
        {
            InitializeComponent();
        }
        private DataSet data_set = new DataSet();
        private string _tabla;

        public void inicio(DataSet ds, string tabla)
        {
            data_set = ds;
            _tabla = tabla;
        }

        private void btnSiguiente_Click(object sender, EventArgs e)
        {
            this.BindingContext[data_set, _tabla].Position += 1;
            this.lblnavegador.Text = 
                Convert.ToString(this.BindingContext[data_set, _tabla].Position + 1);
        }

        private void btnPrimero_Click(object sender, EventArgs e)
        {
            this.BindingContext[data_set, _tabla].Position = 0;
            this.lblnavegador.Text = 
                Convert.ToString(this.BindingContext[data_set, _tabla].Position + 1);

        }

        private void btnAnterior_Click(object sender, EventArgs e)
        {
            this.BindingContext[data_set, _tabla].Position -= 1;
            this.lblnavegador.Text = 
                Convert.ToString(this.BindingContext[data_set, _tabla].Position + 1);
        }

        private void btnUltimo_Click(object sender, EventArgs e)
        {
            this.BindingContext[data_set, _tabla].Position = 
                this.BindingContext[data_set, _tabla].Count - 1;
            this.lblnavegador.Text = 
                Convert.ToString(this.BindingContext[data_set, _tabla].Position + 1);
        }
    }
}

Y por ultimo programamos la clase Program
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MySQLFC
{
    
    
    public class Program
    {
        
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
}

Bueno como se dan cuenta la clase Program contienen el método Main() el cual es el responsable de inicializar todo nuestro programita.

Corriendo Nuestra Aplicacion

Bueno así como en Visual Studio .net solo presionamos F5 y listo tenemos nuestra aplicación funcionando, como podemos ver en la siguiente imagen:

Como pueden ver estoy trabajando en una maquina virtual con Ubuntu; pero ya es tiempo de hacerlo funcionar en Windows, para este fin les comento que mi SO es M$ Windows Vista y solamente tengo el .Net Framework 2.0 instalado, y según todo lo que lei es mas que suficiente para que nuestra aplicación funcione sin problemas, para esto copio la carpeta Debug desde Ubuntu a Windows y lo ejecuto, y veamos.....

Funciona!!!!!!!!!!!!!!!!!, como podemos ver es totalmente cierto que podemos programar aplicaciones que funcionen tanto en LINUX como en WINDOWS, pero saben lo que mas me gusta es que a la inversa también funciona es decir De Windows a Linux, que maravilla con la gente que desarrollo este framework.

Por ultimo debo recordarles que en el Archivo para Descargar se encuentra el Proyecto de MonoDevelop y el script para crear la Base de Datos Facturacion y la DLL correspondiente para poder conectarnos al Servidor MySQL.


Espacios de nombres usados en el código de este artículo:

System
System.Collections.Generic
System.ComponentModel
System.Data
System.Drawing
System.Text
System.Windows.Forms
MySql.Data.MySqlClient



Compromiso del autor del artículo con el sitio del Guille:

Lo comentado en este artículo está probado (y funciona) con la siguiente configuración:

El autor se compromete personalmente de que lo expuesto en este artículo es cierto y lo ha comprobado usando la configuración indicada anteriormente.

En cualquier caso, el Guille no se responsabiliza del contenido de este artículo.

Si encuentras alguna errata o fallo en algún link (enlace), por favor comunícalo usando este link:

Gracias.


Código de ejemplo (comprimido):

 

Fichero con el código de ejemplo: jpa_prog_win_lin.zip - 126.00 KB

(MD5 checksum: 232615246705FCE968A4FFCC12C6E9C7)

 


Ir al índice principal de el Guille