fishScript.com d
Home| Progetto| Web| Faq| Acronimi

Argomenti

Documenti pubblicabili:1120
Scripts:1282
Documenti non pubblicabili:162
Categorie tematiche:68
.Net
   |_C#
   |_Visual basic.net
   |_Asp.net
Active Server Pages
C++
Cascade Style Sheet
JavaScript
Mysql
Php
Xml
Java
   |_Java 2 Micro Edition
   |_Java server pages
   |_Java Servlet
Oracle
   |_PLSQL
PostgreSQL
Unix



Oracle... Script: Loader



PLSQL... Script: TYPE TABLE

Shell scripting... Script: Hide user input on screen

Basically, a web session can be defined as the timeframe in which a visitor navigates your web site.



XPath is a language for addressing parts of an XML document. It is designed to be used by XSLT and XPointer.

Basically, a web session can be defined as the timeframe in which a visitor navigates your web site.

Asp.net

Home >Asp.net > Datagrid

Stampa  Stampa


Scope

The aim of this tutorial is to offer you a jump start into using .Net technologies, in particular how to read trough a web form using a datagrid and some C# code.
In fact, ASP.NET controls such as datagrid allow developers to design quick aspx pages for simple tasks, but usually time consuming, such query and printing the result of a database query.

In this example I will use some C# code and a datagrid control to produce a web page with a simple but stylish results of a Sql query. The compressed file datgrid.zip contains source of the web page and the database.

Requirements

To practice with the following example you need of a web server such as Microsoft Internet Information Server (IIS) running .Net framework. It means that on your local web path you set up a folder such as c:\inetpub\wwwroot\datagrid where it is possible executing an aspx page and reading on Access database. So before beginning, remember you may need to grant these privileges to the aspx page (executing) and Access database (reading).

Suggestions

Maybe the best way to learn this tutorial is:
  1. Extract the zip file in a directory as c:\inetpub\wwwroot\datagrid
  2. Let your browser request the page datagrid.aspx (something as http://localhost/datagrid/datagrid.aspx), if errors occur probably it means you need to grant the necessary privileges as above mentioned
  3. Create an new page (as exercise.aspx) when you have datagrid.aspx listing book data
  4. After reading each paragraph, copy and paste the code in the grey box in your new page exercise.aspx
    You just need to copy at the begin the file the language and namespace directives, including the style sheet file, the C# code within the <script runat="server"> .... </script> and last the web Repeat and Form controls.
  5. When you have finish copying check the page on your browser, probably the .Net Framework Engine will display some "Compilation Error", it means probably you have made some errors while copying the code. Well, you always learn by mistakes, fix them and make your page fly

Books table

First of all, let's make sure you have the mydatabase.mdb Access file, located somewhere such as c:\inetpub\wwwroot\datagrid, containing the books table with the following columns:
  • id (counter)
  • title (text)
  • author (text)
  • pyear (integer)
  • price (currency)
For the sake of the example 2 rows have been inserted:
The Missing World, Margot Livesey, 2000
The King is Dead, Jim Lewis, 2003

The books table should look something like this:

Access Table

Extracting and printing the data

In c:\inetpub\wwwroot\datgrid the file datagrid.aspx contains all the code we need. To achieve our first task, we need C# function that connects to the database and queries and pass the data to a Web Control.
At the top of the page, we need to specify the language used and to import the necessary Namespace (class) containing the OleDb objects we need for database interaction.

<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Data.OleDb" %>


For any C# aspx page the .Net Framework looks for the start-up function Page_Load() that, in our case, calls the function ScrollData().

<script runat="server">
// Tutorial by Marco Magnani
// ©2003 www.fishscript.com
// Use this script as you like it

void Page_Load(Object sender, EventArgs e) {
ScrollData();
}
(...)
</script>


ScrollData() 's duty is to query and to pass the data the Datagrid Web Control, as you can see there is a comment on top of most relevant line of code:



private void ScrollData()
{
//Creation object OleDbConnection
OleDbConnection conn = null;
OleDbDataReader reader = null;
//Construct try/catch
//If something goes bad the catch expression will handle
try
{
//The connection string to the mydatabase.mdb, located in the same folder of this script
string strconn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("mydatabase.mdb");
//Setting up the object conn
conn = new OleDbConnection(strconn);
//Opening the connection
conn.Open();
//Making up the Sql string
string myquery = "SELECT title,author,pyear,price FROM books ORDER BY title";
//Setting up the OleDbCommand
OleDbCommand cmd = new OleDbCommand(myquery, conn);
//Trough the element ExecuteReader(SqlCommand) the query results to the OleDbDataReader
reader = cmd.ExecuteReader();
//Trough the propriety DataSource web control mydatagrid acquires data values
mydatagrid.DataSource = reader;
//Trough web control datagrid, the data is being scrolled
mydatagrid.DataBind();
}
//the catch construct in case connection, query or else goes wrong prints the relative error message
catch (Exception e)
{
Response.Write(e.Message);
Response.End();
}
finally
{
// always call Close when done reading.
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
}

Web control datagrid

As stated above, in this example, it we use the web control datagrid because it really makes easy publish Sql results in a nice and formatted Html table with some Css style.
In fact, for this basic example we just need of the following code:

<asp:DataGrid id="mydatagrid" runat="server"
BorderColor="blue"
BorderWidth="1"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt" AutoGenerateColumns="true">
<HeaderStyle BackColor="#aaaadd">
</HeaderStyle>
</asp:DataGrid>


The property BorderColor,BorderWidth,CellPadding, Font-Name="Verdana", Font-Size="8pt" refers to the layout of the datagrid. You may try to change them with different colour, width, font face and size, etc.
The property AutoGenerateColumns="true" is true anyway by default, it means that the data grid scrolls of the columns of the queried recordset, otherwise, if you se the value to false you need a control for each column. In this example we simply want all the data easy and quick so we just define the colour of the HeaderStyle and request the page in a browser. The page should look something as this:

Final output

Was it quick?






Downloads:
datgrid.zip ( 10 KB)


Warning: include(ads/text468x15.html): failed to open stream: No such file or directory in D:\inetpub\webs\fishscriptcom\documents\view_document.php on line 131

Warning: include(): Failed opening 'ads/text468x15.html' for inclusion (include_path='.;C:\php\pear') in D:\inetpub\webs\fishscriptcom\documents\view_document.php on line 131

Tutorial
Costanti   [C#] 
Enum   [C#] 
Array dichiarazione, inizializzazione, stampa  [C#] 
Array caricamento e stampa attraverso un ciclo for  [C#] 
Array bidimensionali rettangolari inizialiazzazione e stampa  [C#] 
Oggetti (Object) valorizzati con ArrayList, Double, string, proprietà GetType  [C#] 
ArrayList proprietà count, metodo Add, Remove  [C#] 
Jagged array dichiarazione e inizializzazione  [C#] 
Proprietà validare il dato attraverso le proprieta  [C#] 
Overloading creare metodi con lo stesso nome e diverse implementazioni  [C#] 
Programma di cassa da console Tutorial per illustrare l'applicazione di costrutti fondamentali di programmazione come variabili, funzioni condizionali if/then Select/case, cicli, funzioni, oggetti ArrayList Funzioni principali e secondari  [Visual basic.net] 
Array stampa attraverso costrutto for/each  [C#] 
Web controls and C# Sharp (Part II) Saving data in an Access database using a web form   [Asp.net] 
Datagrid Delevoping a simple and quick datagrid to publish query's results  [Asp.net] 
Impostare variabili d’ambiente con .NET Framework 1.1   [C#] 
Script
Controlli e validazione   [Asp.net] 
If Then Costrutti fondamentali  [Visual basic.net] 
Importazione dei namespace Regole sintattiche: importazione delle classi  [Visual basic.net] 
Costrutto If Then Else Costrutti fondamentali  [Visual basic.net] 
Gestione degli errori 1 Iniziare a gestire errori e eccezioni  [Visual basic.net] 
Gestione degli errori 2 Dimostrazione   [Visual basic.net] 
Gestione istruzioni condizionali Costrutto Select/case (Esempio Applicazione da Console)  [Visual basic.net] 
HelloWorld! Iniziare con Visual Basic .Net  [Visual basic.net] 
Intercettare Input da Console Semplice esempio iterazione con l'utente  [Visual basic.net] 
Semplice programma da "console" Iniziare con Visual Basic .Net  [Visual basic.net] 
Leggere Input da Console Iniziare con Visual Basic .Net  [Visual basic.net] 
Lettura di un file di testo Operazioni sul file system: stream di un file e lettura del suo contenuto  [Visual basic.net] 
Lettura di un file Xml con l'oggetto XmlTextReader Parsing di file Xml attraverso i metodi dell'oggetto XmlTextReader  [Visual basic.net] 
Oggetto Date Stampare la data odierna  [Visual basic.net] 
Overloading accesso ad una funzione a secondo del tipo di valore Concetti di base  [Visual basic.net] 
Esercizi
Disegna alcuni tra i più utilizzati controlli di una form Costruire e compilare un form con il Designer di Visual Basic  [Visual basic.net] 
Cicli e operazioni su filesystem Attraverso un ciclo while creare quattro file .txt denominati 4 e i suoi quadrati (4.txt,16.txt,128.txt,2048.txt)  [Visual basic.net] 
File System Data una cartella esegue un copia di tutti i file ivi contenuti  [Visual basic.net] 
Comandi
Ricavare nome e percorso di un'applicazione   [C#] 
Postgres database uptime Last time database has been started (or restarted)  [.Net] 

signal Marco Magnani marcomagnani@fishscript.com



Cerca





A good scientist is a person with original ideas.
A good engineer is a person who makes a design that works with as few original ideas as possible. There are no prima donnas in engineering.
Freeman Dyson


A good scientist is a person with original ideas.
A good engineer is a person who makes a design that works with as few original ideas as possible. There are no prima donnas in engineering.
Freeman Dyson




Oracle... Definizioni: Schema


Shell scripting... Script: while do loop



fishScript.Com is accessible by Mobile access technology as mobile phones, Palm and Pocket PC .

Nicoleta e Marco Magnani tutorial, examples, courses, esempi, corsi, esercizi, appunti vari Dottoressa Nicoleta Dragu Formatrice Docente Insegnante Mediatrice Culturale Dott. Marco Magnani Universita La Sapienza Roma Master Computer Science Hunter College New York , Data Base Administrator DBA oracle System architect

Last modified: 2017-11-30 amministratore@fishscript.comNico and Marco Magnani Software Production
Home|About this Site © 2003-2008 www.fishScript.com ®