Utilizzo di un DataGrid

FAQ di programmazione in .NET

Utilizzo di un DataGrid

Messaggioda alesslud » ven apr 13, 2007 10:32 am

--Creiamo la pagina aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestDataGridConnection.aspx.cs" Inherits="abruzzoparchi_testconnection_TestDataGridConnection" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="Form1" runat="server">

<h3><font face="Verdana">Using an Edit Command Column in DataGrid</font></h3>

<asp:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth="1"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
OnEditCommand="MyDataGrid_Edit"
OnCancelCommand="MyDataGrid_Cancel"
OnUpdateCommand="MyDataGrid_Update"
AutoGenerateColumns="false"
>

<Columns>
<asp:EditCommandColumn
EditText="Edit"
CancelText="Cancel"
UpdateText="Update"
ItemStyle-Wrap="false"
HeaderText="Edit Command Column"
HeaderStyle-Wrap="false"
/>
<!--Queste solo le colonne che abbiamo creato -->
<asp:BoundColumn HeaderText="Nome" ReadOnly="true" DataField="Nome"/>
<asp:BoundColumn HeaderText="Cognome" DataField="Cognome"/>
<asp:BoundColumn HeaderText="Città" DataField="Citta"/>
</Columns>
</asp:DataGrid>

</form>
</body>
</html>


-------------------------------------------------------
Creiamo il bean per accedere ai dati


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyBean
/// </summary>
public class MyBean
{
public MyBean()
{
//
// TODO: Add constructor logic here
//
}

private String nome;
private String cognome;
private String citta;


public void setNome(String nome)
{
this.nome = nome;
}


public String getNome()
{
return nome;
}


public void setCognome(String cognome)
{
this.cognome = cognome;
}


public String getCognome()
{
return cognome;
}


public void setCitta(String citta)
{
this.citta = citta;
}


public String getCitta()
{
return citta;
}
}



--------------------------------------------------------------
Creiamo la classe legata alla .aspx

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class abruzzoparchi_testconnection_TestDataGridConnection : System.Web.UI.Page
{

DataTable cart;
DataView cartView;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["DG6_ShoppingCart"] == null)
{
cart = new DataTable();
//aggiungo l'intestazione di ogni singola colonna
cart.Columns.Add(new DataColumn("Nome", typeof(string)));
cart.Columns.Add(new DataColumn("Cognome", typeof(string)));
cart.Columns.Add(new DataColumn("Citta", typeof(string)));
//Metto in sessione il data table
Session["DG6_ShoppingCart"] = cart;
//mi connetto alla mia classe che esegue l'accesso sul db
MyData myData = new MyData();
//mi carico l'array list
ArrayList myArray = myData.GetDatabases();
// first load -- prepopulate with some data
//aggiungo righe al datagrid nel caso in cui non lo
//abbia in sessione
MyBean myBean = null;
for (int y = 0; y < myArray.Count; y++)
{
DataRow dr = cart.NewRow();

myBean = (MyBean)myArray[y];
dr[0] = myBean.getNome();
dr[1] = myBean.getCognome();
dr[2] = myBean.getCitta();
cart.Rows.Add(dr);
}
}
else
{
//altrimenti mi carico dalla sessione il datagrid
cart = (DataTable)Session["DG6_ShoppingCart"];
}

cartView = new DataView(cart);
cartView.Sort = "Cognome";
if (!IsPostBack)
{
this.BindGrid();
}
}

//utilizzo il seguente metodo per eseguire aggiornamenti del
//datagrid
public void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs e)
{
MyDataGrid.EditItemIndex = (int)e.Item.ItemIndex;
this.BindGrid();
}

//elimina una riga dal datagrid
public void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs e)
{
MyDataGrid.EditItemIndex = -1;
this.BindGrid();
}

//esegue l'aggiornamento del datagrid
public void MyDataGrid_Update(Object sender, DataGridCommandEventArgs e)
{
// For bound columns the edited value is stored in a textbox,
// and the textbox is the 0th element in the column's cell
string nome = e.Item.Cells[1].Text;
string cognome = ((TextBox)e.Item.Cells[2].Controls[0]).Text;
string citta = ((TextBox)e.Item.Cells[3].Controls[0]).Text;

// with a database, we'd use an update command. Since we're using an in-memory
// DataTable, we'll delete the old row and replace it with a new one
//remove old entry
cartView.RowFilter = "nome='" + nome + "'";
if (cartView.Count > 0)
{
//item exists in cart
cartView.Delete(0);
}
cartView.RowFilter = "";

//add new entry
DataRow dr = cart.NewRow();
dr[0] = nome;
dr[1] = cognome;
dr[2] = citta;
cart.Rows.Add(dr);

MyDataGrid.EditItemIndex = -1;
this.BindGrid();
}
//riempie il datagrid
public void BindGrid()
{
MyDataGrid.DataSource = cartView;
MyDataGrid.DataBind();
}
}



--------------------------------------------------------------------
--creiamo la connessione ad un db MySql ed effettuiamo la query

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;
using System.Collections;

/// <summary>
/// Summary description for MyData
/// </summary>
public class MyData
{
public MyData()
{
//
// TODO: Add constructor logic here
//
}

private ConnectionMysql myConnection = new ConnectionMysql();

/**
* ottiene la lista dei risultati del db e li inserisce in un ArrayList.
*/
public ArrayList GetDatabases()
{
ArrayList myArray = new ArrayList();
MySqlDataReader reader = null;

MySqlConnection conn = myConnection.getConnection();
MyBean myBean = null;


MySqlCommand cmd = new MySqlCommand("select * from testdatagrid", conn);
try
{
reader = cmd.ExecuteReader();
while (reader.Read())
{
myBean = new MyBean();
myBean.setNome(reader.GetString(1));
myBean.setCognome(reader.GetString(2));
myBean.setCitta(reader.GetString(3));
myArray.Add(myBean);
}
}
catch (MySqlException ex)
{
Console.WriteLine("Failed to populate database list: " + ex.Message);

}
finally
{
if (reader != null) reader.Close();
}
return myArray;
}
}







---------------------------------------------------
Creiamo la connessione fisica al db

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;

public class ConnectionMysql
{


public MySqlConnection getConnection()
{
MySqlConnection conn = null;
if (conn != null)
conn.Close();

string connStr = String.Format("Server=localhost;Database=abruzzoparchi;Uid=yourusername;Pwd=yourpassword",
"", "", "");

try
{
conn = new MySqlConnection(connStr);
conn.Open();
Console.WriteLine(conn.ToString());

}
catch (MySqlException ex)
{
Console.WriteLine("Error connecting to the server: " + ex.Message);
}
return conn;
}
}



--------------------------------------------------------------
Script per la creazione della tabella

DROP TABLE IF EXISTS `abruzzoparchi`.`testdatagrid`;
CREATE TABLE `abruzzoparchi`.`testdatagrid` (
`ID` int(10) unsigned NOT NULL auto_increment,
`nome` varchar(45) NOT NULL default '',
`cognome` varchar(45) NOT NULL default '',
`citta` varchar(45) NOT NULL default '',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Ultima modifica di alesslud il mar apr 24, 2007 2:43 pm, modificato 1 volta in totale.
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

N.B.

Messaggioda alesslud » ven apr 13, 2007 10:33 am

N.B.: l'update del DataGrid non esegue l'aggiornamento sul db.
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am


Torna a .NET

Chi c’è in linea

Visitano il forum: Nessuno e 1 ospite

cron