Friday, June 25, 2010

What Does Fungus Look Like

DataGridView C # and SQLite with C # on Windows Forms

After seeing how to create a console application in C # to create a database with SQLite, save data and read, we'll see how to do something similar in an application "window" using Windows Forms.

components is done using "normal" rather than the defaults that allow access to databases. We will have a main window that displays the current data in a ListView, and includes a button to add new data:

button "Add" show a second form which will ask the data:

We can do this by following these steps (in Visual C # 2008): Create a new project, which is a "Windows Forms Application" In the main window, add a ListView and a button. Customize ListView using the properties tab, so you have two columns (one for code and one for the name), and as a display mode ("View") have the "details" ("Details" .) Creating a second window from the "Project" in the "Add Windows Form." Add to that window two TextBox for the text that the user entered, along with explanatory text for the Label and a button to confirm. Add the DLL file to your project references (in the window of "Solution Explorer" by right clicking on "References" and selecting the file System.Data.SQLite.DLL from the "Browse" tab.) complete source code of the project. As the code, the two key parts are the part that reads the data to populate the ListView and releasing the auxiliary window, making it what the user type and then enter that data.

The filling in the ListView (which is called the end of the constructor, and after the introduction of new data) could be:

1:
private void ActualizarListaCiudades ( ) 2: {

3: connection
= 4: new

SQLiteConnection
5:
(

"Data Source = personal.sqlite, Version = 3; New = False; Compress = True;"
)

;

6:

connection. Open
(
)
  • ;
  • 7:
  • 8:
  • lstCiudades
  • . Items
. Clear

(

)


;


  9:    10:    / / launch the consultation and prepare to read data structure   11: query string       = "select * from city"   ; 
12: SQLiteCommand cmd = new

SQLiteCommand (
consultation, connection
) ; 13: SQLiteDataReader data Cmd = .

ExecuteReader ( ) ; 14: / / read data repeatedly 15:

while ( data. Read ( ) )

16: {

17: string code = Convert
. ToString (
data [0 ] ) ; 18: string name = Convert .

ToString ( data [1 ] ) ;
19:
/ / And show
20: ListViewItem item = new ListViewItem ( code) ; 21:

item. SubItems . Add
( name) ; 22: lstCiudades . Items . Add (item )

; 23: } 24: connection. Close ( ) ;
25: }

And adding other data would be like: 1: private void InsertarDatos
( string code, string name ) 2: { 3:
4:
insertion string; / / Order of insertion, in SQL 5: cmd SQLiteCommand ; / / Command SQLite 6:
7: connection =
8: new SQLiteConnection 9: ( "Data Source = personal.sqlite, Version = 3, New = False; Compress = True; " )

; 10:
connection. Open

(


)
   ;     11:    12:        try 13: {     
14: insertion = "INSERT INTO city"

+
15: "VALUES ('" + + code
"','" + name +
"');" ;

16:
cmd = new

SQLiteCommand
( insertion,
connection ) ; 17: cmd . ExecuteNonQuery (

) ; 18: } 19:

catch (Exception e
) 20:

{21: MessageBox . Show
( 22: "Unable to insert. Possibly a code is repeated" , 23: "Notice" )

; 24: } 25: connection. Close ( )
; 26: } So the complete action on the button "Add" would be something like

1:
private void btAnadir_Click ( object sender, EventArgs e )
2: {
3: ventanaAnadir . Clean (

) ;
4: ventanaAnadir . ShowDialog ( )
;
5: InsertarDatos ( ventanaAnadir . GetCodigo ( )

, ventanaAnadir .
getName (



)
   )    ;      6:  ActualizarListaCiudades   (   )    
; 7:

} And here you can download the project, with the two sources, the DLL and executable files: csharp_sqlite2.zip

Sunday, June 13, 2010

Email Confidentiality Statement Example

SQLite from C #

SQLite is a database manager, which allows querying using SQL language, and that can be included as part of a program in C or C + +, just including an additional DLL file ... or even that, because it really is a library that can be "embedded" as part of the program. Since C # can not use the SQLite DLL directly, but through others like System.Data.Sqlite.Dll, which can be found in
http://sqlite.phxsoftware.com/ With the DLL, along with the original SQLite, we do programs in C # that allow us to access databases and are easy to distribute. SQLite can be found in http://www.sqlite.org/ We will see a small example of creating a database, how to enter data and display it. First we see the fragments of code, then a full source, then how to compile and test it, and eventually will include the full download, with source, executable and DLLs. To connect to the database, we would create an object of type "SQLiteConnection" connection = new SQLiteConnection ("Data Source = personal.sqlite, Version = 3; New = True; Compress = True , ");
conexion.Open ();
To create and modify queries, create an object of type SQLiteCommand and run it with" ExecuteNonQuery () ": creation string = "CREATE TABLE city" + "(code VARCHAR (2) PRIMARY KEY, name VARCHAR (30 ));"; SQLiteCommand cmd = new SQLiteCommand (creation, connection); cmd.ExecuteNonQuery (); If it is a query that returns data itself (a "select"), use "ExecuteReader ()" and read data repeatedly with "while (datos.Read ())" string query = "select * from city"; SQLiteCommand cmd = new SQLiteCommand (query, conn); SQLiteDataReader data = cmd.ExecuteReader (); / / read data while repeatedly (Datos.Read ()) { string code = Convert.ToString (data [0]); string name = Convert.ToString (data [1]); / / And show Console.WriteLine ("Code : {0}, Name: {1} ", code, name);} In the" ExecuteNonQuery ", we can check the amount of data involved, so we can help you discover errors: quantity = cmd.ExecuteNonQuery (); if (amount \u0026lt;1) Console.WriteLine ("Could not insert");

Still, many types of errors, and a duplicate key, may cause an exception and jumps to interrupt the program, it would be advisable to include insertion orders within a "try ... catch" In any case, at the end of the connection should close access to Database: conexion.Close ();
The full source can be: / / Example of accessing SQLite from C #


/ / Nacho Cabanes, June 2010



using System;

using System. IO

;


using System
.
Data

.

SQLite
 ;   


//Utilizamos la DLL




public
   

class

pruebaSQLite01

{


  
static

SQLiteConnection conexion

;





private


static


 void 

CrearBBDDSiNoExiste

(



)




 

{if





(
 !  File 
.

Exists (

"personal.sqlite" )
) {
/ / Create the connection to the database. / / The Source Data File contains the path of the database connection

= new

SQLiteConnection ( "Data Source = personal.sqlite, Version = 3; New = True; Compress = True;"
) ;
connection. Open
(
) ; / / Create the first table creation string = "CREATE TABLE city"

+ ( code VARCHAR (2) PRIMARY KEY, name VARCHAR (30)); "
; SQLiteCommand cmd = new SQLiteCommand ( creation, connection ) ;
cmd.
ExecuteNonQuery (
)
;
/ / Create the second table creation

= "CREATE TABLE person" + ( code VARCHAR (2) PRIMARY KEY, name VARCHAR (30), " + " codigoCiudad VARCHAR (2)); " ;

cmd = new SQLiteCommand ( creation, connection
)

;
cmd.
ExecuteNonQuery ( )

; } else { / / Create the connection to the database.
/ / The Source Data File contains the path of the database connection = new SQLiteConnection
(
"Data Source = personal.sqlite, Version = 3, New = False; Compress = True; "

)
;
connection. Open
( )
; }}
private static void
InsertarDatos ( ) {

insertion string;
/ / Order of insertion, in SQL SQLiteCommand
cmd;

/ / SQLite Command

int
amount ;
/ / Result: The amount of data
try { insertion
= "INSERT INTO city" + " VALUES ('t', 'Toledo'); " ; cmd = new

SQLiteCommand (
insertion, connection
)

; cmd = amount . ExecuteNonQuery ( )

;
if
( amount \u0026lt;
1)
Console.
WriteLine ( "Could not insert" )

;

insertion
= "INSERT INTO city" +
"VALUES ('a', 'Alicante');" ;
cmd = new SQLiteCommand
( insertion, connection ) ; amount cmd = .

ExecuteNonQuery ( ) ; if (
amount \u0026lt; 1 ) Console. WriteLine (

"Could not insert" ) ; insertion = "INSERT INTO person"

+ "VALUES (' j ',' John ',' t '); " ;
cmd = new SQLiteCommand

( insertion, connection ) ; amount cmd = .
ExecuteNonQuery ( ) ; if (

amount \u0026lt; 1) Console. WriteLine (
"Could not insert" ) ; insertion = "INSERT INTO person"


+ "VALUES ('p', 'Pepe', 't');" ;
cmd = new SQLiteCommand
( insertion, connection ) ; amount cmd = .

ExecuteNonQuery ( ) ; if (
amount \u0026lt; 1) Console. WriteLine (

"Could not insert" ) ; }

catch (Exception e
) {

Console. WriteLine ( "Could not insert" ) ; Console.
WriteLine ( "Possibly a code is repeated" ) ; Console.

WriteLine ( "Error found: {0}" , and . Message )
; } }

private
static void MostrarCiudades ( )
{
/ / launch the consultation and prepare to read data structure string query = "select * from city" ; SQLiteCommand cmd = new

SQLiteCommand ( consultation, connection ) ;
SQLiteDataReader data = cmd . ExecuteReader ( ) ; / / read data repeatedly

while (
data.
Read
( ) ) {string code = Convert
.
ToString (
data [
0 ] )
; string name = Convert . ToString ( data [1

] ) ; / / And show
Console.
WriteLine (
"Code: {0}, Name: {1}" , code, name ) ; }

}
private static void MostrarPersonas ( ) {

/ / launch the consultation and prepare the structure for reading data query string = "select * from person" ; SQLiteCommand cmd = new SQLiteCommand ( consultation,
connection )

;
SQLiteDataReader data = cmd . ExecuteReader (
) ; / / read data repeatedly
while
(
data.
Read

( ) ) {string code = Convert
. ToString (

data [0
] )
; string name = Convert . ToString ( data [1

] ) ; / / And show
Console.
WriteLine (
"Code: {0}, Name: {1}" , code, name ) ; }

}
private static void MostrarCiudadesYPersonas ( ) {

/ / launch the consultation and prepare to read data structure string query = "persona.nombre select a city. name " +" from person town " + " where persona.codigoCiudad = ciudad.Codigo " ; SQLiteCommand cmd = new
SQLiteCommand

(
consultation , connection ) ; SQLiteDataReader data = cmd
. ExecuteReader ( )
;

/ / read data repeatedly

while ( data. Read ( ) )
{

nombrePersona string Convert
=
.
ToString (
data [0
] )

; string Convert nombreCiudad = . ToString ( data [1
] ) ; / / And show
Console.

WriteLine (
"{0} lives at {1}" , nombrePersona , nombreCiudad ) ;
} }
private static void CerrarBBDD ( ) {

connection. Close ( ) ; } public
static

void
Main ( ) {
Console . WriteLine ( "Accediendo..." )
;

CrearBBDDSiNoExiste (

) ; Console. WriteLine ( "Adding data ..." )
;

InsertarDatos ( ) ; Console.
WriteLine (
"city data"

) ; MostrarCiudades ( ) ;

Console.
WriteLine ( "data people" ) ; MostrarPersonas (
) ; Console.

WriteLine ( "data people and cities," ) ; MostrarCiudadesYPersonas (
) ; CerrarBBDD (
) ; } }

To compile this source, we include "System.Data . SqLite.dll "within the project references. This would be done from within the visual environment if we use tools like Visual Studio or SharpDevelop, or by adding the / r option if you compile from the command line, for example using Mono: gmcs pruebaSQLite.cs / r: System.Data. SqLite.dll
And here you can download the source, the DLL and executable files: csharp_sqlite.zip

Monday, June 7, 2010

Breathlessness With Blood Sugar

Playing with C #

If you want to learn C # from scratch (or almost), you can read my introductory course in: http://www.nachocabanes.com/csharp/curso/
There is also a forum where questions about C # consulting in AprendeAProgramar.com, which is easy to find: http://www. aprendeaprogramar.com / mod / forum / view.php? id = 372 But sometimes experiment with other themes, not as "for beginners", such as access to databases from C # using SQLite or creating Tao.Sdl games. Many of these issues will be published here, and only the most basic way is open to appear as part of the course. If you are interested ... peek in the coming days ... ;-)