December
11
2008

corso c sharp realizzare un form da mandare al db per eseguire le queries

Tutorial->Programmazione-tutorial->tutorial C Sharp

File aspx.cs

  1.  
  2. using System;
  3. using System.Collections;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.Data.SqlClient;
  13. public partial class sendsql : System.Web.UI.Page
  14. {
  15.     protected void Page_Load(object sender, EventArgs e)
  16.     {
  17.  
  18.     }
  19.     protected void senddati_Click(object sender, EventArgs e)
  20.     {
  21.         string strConn = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString; ;
  22.         System.Data.SqlClient.SqlConnection Myc = new System.Data.SqlClient.SqlConnection(strConn);
  23.         Myc.Open();
  24.         SqlCommand Mycommand = new SqlCommand(TxtSql.Text, Myc);
  25.         try
  26.         {
  27.             int rows = Mycommand.ExecuteNonQuery();
  28.  
  29.             TxtSql.Text += "Righe affected" + rows.ToString();
  30.         }
  31.         catch (Exception error) {
  32.             TxtSql.Text += error.Message ;
  33.         }
  34.  
  35.     }
  36. }
  37.  
  38.  
  39.  

File aspx

  1. <asp:content id="Content1" contentplaceholderid="head" runat="Server"> </asp:content>
  2. <asp:content id="Content2" contentplaceholderid="ContentPlaceHolder1" runat="Server">  <asp:textbox id="TxtSql" runat="server" height="93px" width="371px"> Testo </asp:textbox> <asp:button id="senddati" runat="server" text="Send Sql" onclick="senddati_Click"></asp:button> </asp:content>

In questo caso abbiamo usato una Master Page per il layout del sito, cosa che si invita a rispettare per evitare duplicati del codice.

Usiamo l'oggetto SqlCommand per mandare i dati attraverso il metodo ExecuteNonQuery.

Se la sintassi non viene ben scritta, riceviamo un errore che viene catturato per mezzo del catch.





Pagina 0 di 1
Ordina per Nome Data