Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

MODIFICATION ET SUPPRESSION D'ENREGISTREMENT DANS UNE BASE DE DONNÉES


Information sur la source

Catégorie :ASP.Net Source .NET ( DotNet ) Niveau : Débutant Date de création : 23/05/2002 Date de mise à jour : 23/05/2002 13:06:49 Vu / téléchargé: 10 901 / 755

Note :
9,67 / 10 - par 3 personnes
9,67 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

Description

Cette portion de code vous permettra d'interagir avec la base de données (UPDATE et DELETE) via un contrôle DATAGRID
 

Source

  • <%@ Page Language="VB" %>
  • <%@ Import Namespace="System.Data" %>
  • <%@ Import Namespace="System.Data.OleDb" %>
  • <script runat="server">
  • ' On définit la connection
  • Dim Conn As New OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & Server.MapPath("\testnet\test.mdb"))
  • sub Page_Load(obj as Object, e as EventArgs)
  • if Not Page.IsPostBack then
  • FillDataGrid()
  • end if
  • end sub
  • sub dgData_Edit(obj as object, e as DataGridCommandEventArgs)
  • FillDataGrid(e.Item.ItemIndex)
  • end sub
  • sub dgData_Delete(obj as object, e as DataGridCommandEventArgs)
  • dim strSQL as string = "DELETE FROM CLIENT WHERE CL_ID = " & Ctype(e.Item.Cells(0).Controls(1), Label).Text
  • ExecuteStatement(strSQL)
  • FillDataGrid()
  • end sub
  • sub dgData_Update(obj as object, e as DataGridCommandEventArgs)
  • if UpdateDataStore(e) then
  • FillDataGrid(-1)
  • end if
  • end sub
  • sub dgData_Cancel(obj as object, e as DataGridCommandEventArgs)
  • FillDataGrid(-1)
  • end sub
  • function UpdateDataStore(e as DataGridCommandEventArgs) as boolean
  • dim i,j as integer
  • dim tabUpdate(1) as string
  • dim strText as string
  • dim blnGo as boolean = true
  • j = 0
  • ' -3 pour ne pas compter les colonnes EDITION et SUPPRESSION
  • for i = 1 to e.Item.Cells.Count - 3
  • strText = Ctype(e.Item.Cells(i).Controls(0), TextBox).Text
  • ' Combien de colonnes : e.Item.Cells.Count
  • ' 9 cellules : ID, nom, etc...suppression
  • if strText <> "" then
  • tabUpdate(j) = strText
  • j = j + 1
  • else
  • blnGo = false
  • lblMessage.Text = "Veuillez renseigner tous les champs svp"
  • end if
  • next
  • if not blnGo then
  • return false
  • exit function
  • end if
  • dim strSQL as string = "UPDATE CLIENT SET " & _
  • "CL_NOM = '" & tabUpdate(0) & "'," & _
  • "CL_VILLE = '" & tabUpdate(1) & "'" & _
  • " WHERE CL_ID = " & Ctype(e.Item.Cells(0).Controls(1), Label).text
  • ExecuteStatement(strSQL)
  • return blnGo
  • end function
  • sub FillDataGrid(Optional EditIndex as integer=-1)
  • 'Ouverture de la connexion
  • dim objCmd as new OleDbCommand ("select * from CLIENT", Conn)
  • dim objReader as OleDbDataReader
  • try
  • objCmd.Connection.Open()
  • objReader = objCmd.ExecuteReader()
  • catch ex as Exception
  • lblMessage.Text = "Liaison avec la base de données erronée"
  • end try
  • dgData.DataSource = objReader
  • if not EditIndex.Equals(Nothing) then
  • dgData.EditItemIndex = EditIndex
  • end if
  • dgData.DataBind()
  • objReader.Close
  • objCmd.Connection.Close()
  • end sub
  • function ExecuteStatement(strSQL)
  • dim objCmd as new OleDbCommand(strSQL, Conn)
  • try
  • objCmd.Connection.Open()
  • objCmd.ExecuteNonQuery()
  • catch ex as Exception
  • lblMessage.Text = "Erreur lors de la mise à jour des données"
  • end try
  • objCmd.Connection.Close()
  • end function
  • </script>
  • <html>
  • <body>
  • <asp:Label id="lblMessage" runat="server"/>
  • <form runat="server">
  • <asp:DataGrid id="dgData" runat="server"
  • BorderColor="black"
  • GridLines="Vertical"
  • cellpadding="4"
  • cellspacing="0"
  • width="450"
  • Font-Names="Arial"
  • Font-Size="8pt"
  • ShowFooter="True"
  • HeaderStyle-BackColor="#CCCCCC"
  • FooterStyle-BackColor="#CCCCCC"
  • ItemStyle-BackColor="#ffffff"
  • AlternatingItemStyle-Backcolor="#cccccc"
  • AutoGenerateColumns="False"
  • OnDeleteCommand="dgData_Delete"
  • OnEditCommand="dgData_Edit"
  • OnCancelCommand="dgData_Cancel"
  • OnUpdateCommand="dgData_Update">
  • <Columns>
  • <asp:TemplateColumn HeaderText="ID">
  • <ItemTemplate>
  • <asp:Label id="Id" runat="server" Text='<%# Container.DataItem("CL_ID") %>'/>
  • </ItemTemplate>
  • </asp:TemplateColumn>
  • <asp:BoundColumn HeaderText="Nom" DataField="CL_NOM" />
  • <asp:BoundColumn HeaderText="Ville" DataField="CL_VILLE"/>
  • <asp:EditCommandColumn
  • EditText="Edition"
  • CancelText="Annuler"
  • UpdateText="Mise à jour"
  • HeaderText="Edition"/>
  • <asp:ButtonColumn HeaderText="Suppression" text="Supprimer" CommandName="delete" />
  • </Columns>
  • </asp:DataGrid>
  • </form>
  • </body>
  • </html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>

<script runat="server">
	' On définit la connection
   	Dim Conn As New OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & Server.MapPath("\testnet\test.mdb"))
   
   	sub Page_Load(obj as Object, e as EventArgs) 
		if Not Page.IsPostBack then
			FillDataGrid()
      	end if
   	end sub
   
	sub dgData_Edit(obj as object, e as DataGridCommandEventArgs)
      	FillDataGrid(e.Item.ItemIndex)
   	end sub
    
   	sub dgData_Delete(obj as object, e as DataGridCommandEventArgs)
      	dim strSQL as string = "DELETE FROM CLIENT WHERE CL_ID = " & Ctype(e.Item.Cells(0).Controls(1), Label).Text
	  
	  	ExecuteStatement(strSQL)
       
      	FillDataGrid()
   	end sub
    
   	sub dgData_Update(obj as object, e as DataGridCommandEventArgs)
      	if UpdateDataStore(e) then
         	FillDataGrid(-1)
      	end if
   	end sub
   
   	sub dgData_Cancel(obj as object, e as DataGridCommandEventArgs)
      	FillDataGrid(-1)
   	end sub
    
   	function UpdateDataStore(e as DataGridCommandEventArgs) as boolean
       
      dim i,j as integer
      dim tabUpdate(1) as string
      dim strText as string
      dim blnGo as boolean = true
      
      j = 0
      
      ' -3 pour ne pas compter les colonnes EDITION et SUPPRESSION
	  for i = 1 to e.Item.Cells.Count - 3
         strText = Ctype(e.Item.Cells(i).Controls(0), TextBox).Text
         
		 ' Combien de colonnes : e.Item.Cells.Count
		 ' 9 cellules : ID, nom, etc...suppression
		 
		 
		 if strText <> "" then
			tabUpdate(j) = strText
            j = j + 1
         else
            blnGo = false
            lblMessage.Text = "Veuillez renseigner tous les champs svp"
         end if
      next
      
      if not blnGo then
         return false
         exit function
      end if
       
      dim strSQL as string = "UPDATE CLIENT SET " & _
         "CL_NOM = '" & tabUpdate(0) & "'," & _
         "CL_VILLE = '" & tabUpdate(1) & "'" & _
         " WHERE CL_ID = " & Ctype(e.Item.Cells(0).Controls(1), Label).text

      	ExecuteStatement(strSQL)
      return blnGo
   end function
    
   sub FillDataGrid(Optional EditIndex as integer=-1)
      'Ouverture de la connexion
      dim objCmd as new OleDbCommand ("select * from CLIENT", Conn)
      dim objReader as OleDbDataReader
      
      try
         objCmd.Connection.Open()
         objReader = objCmd.ExecuteReader()
      catch ex as Exception
         lblMessage.Text = "Liaison avec la base de données erronée"
      end try
      
      dgData.DataSource = objReader
      if not EditIndex.Equals(Nothing) then
         dgData.EditItemIndex = EditIndex
      end if
      
      dgData.DataBind()
       
      objReader.Close
      objCmd.Connection.Close()
       
   end sub
    
   function ExecuteStatement(strSQL) 
      dim objCmd as new OleDbCommand(strSQL, Conn)
      
      try
         objCmd.Connection.Open()
         objCmd.ExecuteNonQuery()
      catch ex as Exception
		lblMessage.Text = "Erreur lors de la mise à jour des données"
      end try
      
      objCmd.Connection.Close()
   end function
</script>

<html>
<body>
	<asp:Label id="lblMessage" runat="server"/>
   	
	<form runat="server">
		<asp:DataGrid id="dgData" runat="server"
        	BorderColor="black"
            GridLines="Vertical"
            cellpadding="4"
            cellspacing="0"
            width="450"
            Font-Names="Arial"
            Font-Size="8pt"
            ShowFooter="True"
            HeaderStyle-BackColor="#CCCCCC"
            FooterStyle-BackColor="#CCCCCC"
            ItemStyle-BackColor="#ffffff"
            AlternatingItemStyle-Backcolor="#cccccc"
            AutoGenerateColumns="False"
			OnDeleteCommand="dgData_Delete"
         	OnEditCommand="dgData_Edit"
         	OnCancelCommand="dgData_Cancel"
         	OnUpdateCommand="dgData_Update">

         	<Columns>
            	<asp:TemplateColumn HeaderText="ID">
              		<ItemTemplate>
                 		<asp:Label id="Id" runat="server" Text='<%# Container.DataItem("CL_ID") %>'/>
              		</ItemTemplate>
            	</asp:TemplateColumn>
            
            	<asp:BoundColumn HeaderText="Nom" DataField="CL_NOM" />
            	<asp:BoundColumn HeaderText="Ville" DataField="CL_VILLE"/>
            
            	<asp:EditCommandColumn
               		EditText="Edition"
               		CancelText="Annuler"
               		UpdateText="Mise à jour"
               		HeaderText="Edition"/>
            
            	<asp:ButtonColumn HeaderText="Suppression" text="Supprimer" CommandName="delete" />
         	</Columns>
		</asp:DataGrid>
   </form>
</body>
</html> 

Conclusion

Bonne programmation

A+
 

Fichier Zip

Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

Commentaires et avis

signaler à un administrateur
Commentaire de dedzep le 29/09/2003 17:27:54

parfait
fonctionne bien pour un debutant comme moi
mais existe-t'il un datagrid regroupant modif/suppr/ajout ?
un datagrid permettant de voir pour une un fichier commande les articles y afferants ?

bravo à ceux qui transmettent leur savoir

signaler à un administrateur
Commentaire de ljemal le 23/09/2004 18:20:13

qqun peut m'aider

mon navigateur affiche tout blanc ! c-a-d rien

Ajouter un commentaire



Nos sponsors

Sondage...

CalendriCode

Décembre 2008
LMMJVSD
1234567
891011121314
15161718192021
22232425262728
293031    

Consulter la suite du CalendriCode



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel BAÏSE, Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,265 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.