C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

19
C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz. Página 1 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/ C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz. All Rigths Reserved. Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación. Egresado del Instituto Tecnológico de Orizaba, Ver. (México).

description

Se muestra como programar en C# un DataGridView no atado.M.C. Enrique Ruiz Díaz.

Transcript of C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

Page 1: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 1 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

All Rigths Reserved.

Con título y cédula profesional 5632071 en la Maestría en Ciencias de la Computación.

Egresado del Instituto Tecnológico de Orizaba, Ver. (México).

Page 2: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 2 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Acerca de mi.

Titulado en la Maestría en Ciencias en Ciencias de la Computación, Cédula profesional 5632071. Egresado del Instituto

Tecnológico de Orizaba, Ver., México. Antes, me Titulé en la Licenciatura en Informática, Cédula profesional 4046033. Egresado

del Instituto Tecnológico de Tuxtepec, Oax., México, distinguiéndome además, por ser el mejor promedio de mi generación con

98%.

Bien, regresando al tema de mi Título de Maestría en Ciencias de la Computación, para subrayar que ésta, requirió el desarrollo de

una TESIS. Otro aspecto muy importante, fue que durante el desarrollo de mi Maestría escribí un ARTICULO, mismo que fue

aceptado para publicación y con mi ponencia en el evento 'Primer Encuentro de Estudiantes en Ciencia de la Computación - E2C2'

ISBN-10:970-36-0404-8 e ISBN-13:978-970-36-0404-3 celebrado en el Instituto Politécnico Nacional, México, D.F. 2007.

Page 3: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 3 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Mi Diploma por mi Ponencia en el Instituto Politécnico Nacional, México, D.F. 2007.

Page 4: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 4 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

«Inside the great field of the Programming, I own to offer my knowledge of the Structured Programming Paradigm. This,

principally by means of the Language C. Also, I own to offer my knowledge of the Object-Oriented Paradigm. This, by means of

The Languages Java and Visual C#. Majorly».

M.C. Enrique Ruiz Díaz.

Page 5: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 5 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

ÍNDICE Acerca de mi. ............................................................................................................................................................. 2

ÍNDICE ........................................................................................................................................................................ 5

1. Objetivos logrados. ................................................................................................................................................ 6

1.1. Para el usuario final. ......................................................................................................................................... 6

1.2 Para el programador. ........................................................................................................................................ 6

1.3. Comentario. ..................................................................................................................................................... 6

2. ¿Por qué el DataGridView como no atado, es decir, independiente, y no el atado?. ............................................ 7

3. Especificando al DataGridView como no atado, al arrastrarlo y soltarlo en la aplicación. ..................................... 8

4. Cómo aparece la aplicación en la parte de diseño visual. ...................................................................................... 9

5. Desglose de elementos de “arrastrar y soltar” en el formulario de la aplicación. ............................................... 10

6. Cómo aparece la aplicación ejecutandose ante el usuario final. .......................................................................... 12

7. Cómo debe proceder el usuario final para seleccionar un registro (renglón) o varios de estos a la vez. ............. 13

8. Código fuente del Programa. ............................................................................................................................... 14

Page 6: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 6 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

1. Objetivos logrados.

1.1. Para el usuario final.

1) Desplegar el instrumento DataGridView como un presentador de registros (renglones) de información.

2) Permitirse el modificar datos.

3) Inhabilitar la posibilidad de modificar datos.

4) Indicar que sólo un registro puede ser seleccionado a la vez.

5) Indicar que múltiples registros pueden ser seleccionados.

6) Eliminar registros previamente seleccionados.

7) Habilitar el poder agregar registros.

8) Desplegar el contenido de registros seleccionados.

1.2 Para el programador.

A través del presente documento, el programador conocerá cómo codificar las instrucciones que permiten llevar a cabo las operaciones ya referidas en

el punto 1.1. anterior.

1.3. Comentario.

Es el programador el que decide que facultades se otorgan al usuario final, y que facultades se reserva él. En el programa de ejemplo aquí mostrado, el

usuario final recibió todas las facultades ya referidas.

Page 7: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 7 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

2. ¿Por qué el DataGridView como no atado, es decir, independiente, y no el atado?.

La respuesta más obvia a esta pregunta es que el presente documento se enfocó en el DataGridView no atado, y no en el atado

como objeto de estudio. Entonces se hace evidente que el DataGridView atado será objeto de otro estudio aparte. Bien, ahora

debo decir que el DataGridView no atado resulta atrayente porque atorga al Programador avispado (es decir, hábil para codificar)

el control y los beneficios de esta poderosa herramienta enteramente a su responsabilidad.

Por supuesto que conocer al DataGridView atado (ahora no estudiado) también es importante, pero ese DataGridView implica

para el programador otros compromisos (computacionalmente hablando) de los cuales debe estar muy bien documentado para

que no le resulte contraproducente. En consecuencia, como ya dije, si se sabe programamar bien, el presente estudio resulta ser

un comienzo conveniente.

Page 8: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 8 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

3. Especificando al DataGridView como no atado, al arrastrarlo y soltarlo en la aplicación.

Insertando a través de arrastrar y soltar al DataGridView en la aplicación.

Observe que al arrastrar y soltar el DataGridView en la aplicacón, no modificamos los datos de configuración que

ya inicialmente nos provee. Observe que el valor para «Choose Data Source» permanece como «none». Esto

último significa que el DataGridView no está atado a alguna fuente de datos.

Page 9: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 9 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

4. Cómo aparece la aplicación en la parte de diseño visual.

La Aplicación, ante el usuario final.

Page 10: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 10 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

5. Desglose de elementos de “arrastrar y soltar” en el formulario de la aplicación.

El desglose es de izquierda a derecha, y de arriba abajo.

Tipo de elemento Nombre

Button Show_DataGridView

dataGridView dataGridView1

Button button1_Allow_to_Modify_data

Button button_Do_not_Allow_to_modify_data

Label label1

Button button_Only_a_selected_row

Button button1_Allow_multiple_selection_of_rows

Label label2

Button button1_delete_selected_rows

Page 11: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 11 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

Button button1_Allow_to_add_rows

Button boton_Show_me_the_selected_row

Label label3

Page 12: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 12 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

6. Cómo aparece la aplicación ejecutandose ante el usuario final.

La Aplicación en ejecución.

Page 13: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 13 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

7. Cómo debe proceder el usuario final para seleccionar un registro (renglón) o varios de estos a la vez.

El DataGridView con tres registros seleccionados.

Observe que al comienzo de cada registro (renglón) existe un pequeño recuadro, que provisionalmente

llamaremos “celda para seleccionar”. Bien, si sólo se requiere seleccionar un registro, únicamente se requiere dar

un clic en la celda para seleccionar correspondiente. Ahora, si se requiere seleccionar más de un registro a la vez,

entonces primero se oprime la tecla CONTROL y se conserva oprimida, con esto, ya se puede usar la referida celda

para seleccionar con los registros deseados.

Page 14: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 14 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

8. Código fuente del Programa.

// Inicio del código.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

// Versión definitiva: hoy 28 December 2012.

namespace GridView_1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)

Page 15: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 15 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

{

label1.Text = "";

label2.Text = "";

}

private void Show_DataGridView_Click(object sender, EventArgs e)

{

// Dos lineas siguientes: Para el DataGridView: Crear Columnas y nombres de sus columnas.

int total_of_Columns = 5;

string[] Columns_names = new string[] { "Product ID", "Product Name", "Product Price", "Product Category",

"Product Description" };

Create_Columns_to_DataGridView(total_of_Columns, Columns_names);

// **************************************************************************

// Asunto siguiente: Agregar las filas al DataGridView, con datos.

string[] row = new string[] { "31", "Product 1", "1000", "Babies", "Pañales" };

Add_newRow_to_DataGridView(row);

row = new string[] { "32", "Product 2", "2000", "Electronics", "TV" };

Add_newRow_to_DataGridView(row);

row = new string[] { "33", "Product 3", "3000", "Ladies", "clothes" };

Add_newRow_to_DataGridView(row);

row = new string[] { "34", "Product 4", "4000", "Gentlemen", "clothes" };

Add_newRow_to_DataGridView(row);

row = new string[] { "35", "Product 5", "5000", "Music", "CD" };

Add_newRow_to_DataGridView(row);

row = new string[] { "36", "Product 6", "6000", "Movies", "DVD" };

Add_newRow_to_DataGridView(row);

Page 16: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 16 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

row = new string[] { "37", "Product 7", "7000", "Toys", "Balls" };

Add_newRow_to_DataGridView(row);

row = new string[] { "39", "Product 9", "9000", "Spices", "Red peppers" };

Add_newRow_to_DataGridView(row);

// ***************************************************************************************

}

private void Create_Columns_to_DataGridView(int cantidad, string[] Columns_names)

{

dataGridView1.ColumnCount = cantidad;

for (int i = 0; i < cantidad; i++)

{

dataGridView1.Columns[i].Name = Columns_names[i];

}

// El usuario no tiene permiso de agregar filas, con la siguiente -

// opcion en false.

dataGridView1.AllowUserToAddRows = false;

}

private void Add_newRow_to_DataGridView(string[] row)

{

dataGridView1.Rows.Add(row);

}

Page 17: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 17 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

private void button_Only_a_selected_row_Click(object sender, EventArgs e)

{

dataGridView1.MultiSelect = false;

label2.Text = "Present specification: Only a row.";

button_Only_a_selected_row.Hide();

button1_Allow_multiple_selection_of_rows.Show();

}

private void button1_Allow_multiple_selection_of_rows_Click(object sender, EventArgs e)

{

dataGridView1.MultiSelect = true;

label2.Text = "Present specification: Multiple rows.";

button1_Allow_multiple_selection_of_rows.Hide();

button_Only_a_selected_row.Show();

}

private void button1_Allow_to_Modify_data_Click(object sender, EventArgs e)

{

dataGridView1.ReadOnly = false;

label1.Text = "Present specification: yes, to Modify";

button1_Allow_to_Modify_data.Hide();

button_Do_not_Allow_to_modify_data.Show();

}

private void button_Do_not_Allow_to_modify_data_Click(object sender, EventArgs e)

{

dataGridView1.ReadOnly = true;

label1.Text = "Present specification: Not, to Modify";

button_Do_not_Allow_to_modify_data.Hide();

Page 18: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 18 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

button1_Allow_to_Modify_data.Show();

}

private void boton_Show_me_the_selected_row_Click(object sender, EventArgs e)

{

if (dataGridView1.SelectedRows.Count > 0)

{

string datos = "";

int Cantidad_celdas = dataGridView1.SelectedRows[0].Cells.Count;

for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)

{

for (int t = 0; t < Cantidad_celdas; t++)

{

try

{

datos = datos + dataGridView1.SelectedRows[i].Cells[t].Value.ToString() + ", ";

}

catch

{

//si el usuario deja una celda vacía, -

// el sistema lo considera 'null', y no -

// como string = " ".

datos = datos + " ";

} // fin del try...catch

}// fin del 'ciclo for' más interno.

MessageBox.Show("Fila seleccionada: " + " datos: " + datos);

datos = "";

} // fin del primer 'ciclo for'. El más externo.

}

else

{

MessageBox.Show("Usuario: actualmente, no tiene fila alguna seleccionada.");

Page 19: C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz

C# and The Unattached DataGridView, by M.C. Enrique Ruiz Díaz.

Página 19 de 19 Visit: https://sites.google.com/site/mcenriqueruizdiaz/ Also: http://sites.google.com/site/enriqueruizdiaz/

}

}

private void button1_delete_selected_rows_Click(object sender, EventArgs e)

{

if (dataGridView1.SelectedRows.Count == 0)

{

MessageBox.Show("Usuario: No se pueden borrar filas, porque actualmente no hay fila(s)

seleccionadas.");

return;

}

if (dataGridView1.SelectedRows.Count == dataGridView1.Rows.Count)

{

dataGridView1.Rows.Clear();

}

foreach (DataGridViewRow row in dataGridView1.SelectedRows)

{

dataGridView1.Rows.Remove(row);

}

}

private void button1_Allow_to_add_rows_Click(object sender, EventArgs e)

{

// Se otorga al usuario, la capacidad de agregar filas.

MessageBox.Show("Usuario: Se le habilitó la capacidad de agregar registros.");

dataGridView1.AllowUserToAddRows = true;

}

}

}

// Fin del código.