2012-07-19 6 views
1

J'ai un MultiView pour ajouter des employés qui a 3 vues. S'il vous plaît laissez-moi savoir le bon chemin. Voici le mauvais code que j'ai fait qui ne fonctionne pas. Il va donner de nouvelles erreurs chaque fois que je modifie quelque chose.Enregistrement en utilisant MultiView ne fonctionne pas

Désolé je ne parvente pas de code postal ici. Voici le message sur le forum ASP.NET

http://forums.asp.net/t/1825476.aspx/1?Registration+using+MultiView+not+working+

namespace EmployeeMultiView.AdminPages 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!Page.IsPostBack) 
       MultiView1.ActiveViewIndex = 0; 
     } 

     private void InsertInfo() 
     { 
      String KKSTechConnectionString = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True"; 
      SqlConnection conn = new SqlConnection(KKSTechConnectionString); 
      //Session["sessFirstName"] = Request["textbox1"]; 

       try 
       { 
       conn.Open(); 
       String insertstring = @"Insert INTO Emp 
       (EmpID,FirstName,LastName,MiddleName,Mob1,Mob2,Phone,Email1,Email2,EmpDesc,Accno,IFSCCode,Branch,ApproxUnitPrice) 
       values (@EmpID,@FirstName,@LastName,@MiddleName,@Mob1,@Mob2,@Phone,@Email1,@Email2,@EmpDesc,@Accno,@IFSCCode,@Branch,@ApproxUnitPrice)"; 



       if (MultiView1.ActiveViewIndex == 0) 
       { 
        SqlCommand cmd = new SqlCommand("insertstring", conn); 
        cmd.CommandText = insertstring; 
        cmd.CommandType = CommandType.Text; 

        cmd.Parameters.AddWithValue("@EmpID", TextBox1.Text); 
        cmd.Parameters.AddWithValue("@FirstName", TextBox2.Text); 
        cmd.Parameters.AddWithValue("@LastName", TextBox3.Text); 
        cmd.Parameters.AddWithValue("@MiddleName", TextBox4.Text); 
        cmd.Parameters.AddWithValue("@Mob1", TextBox5.Text); 
        cmd.Parameters.AddWithValue("@Mob2", TextBox6.Text); 
        cmd.Parameters.AddWithValue("@Phone", TextBox7.Text); 
        cmd.Parameters.AddWithValue("@Email1", TextBox8.Text); 
        cmd.Parameters.AddWithValue("@Email2", TextBox9.Text); 
        cmd.Parameters.AddWithValue("@EmpDesc", TextBox10.Text); 
        } 

       else if (MultiView1.ActiveViewIndex == 1) 
       { 
        SqlCommand cmd2 = new SqlCommand("insertstring", conn); 
        cmd2.CommandText = insertstring; 
        cmd2.CommandType = CommandType.Text; 

        cmd2.Parameters.AddWithValue("@Accno", TextBox11.Text); 
        cmd2.Parameters.AddWithValue("@IFSCCode", TextBox12.Text); 
        cmd2.Parameters.AddWithValue("@Branch", TextBox13.Text); 
        cmd2.Parameters.AddWithValue("@ApproxUnitPrice", TextBox16.Text); 
        cmd2.ExecuteNonQuery(); 
       } 
       else if (MultiView1.ActiveViewIndex == 2) 
       { 
        if (FileUpload1.HasFile) 
        { 
         byte[] productImage = FileUpload1.FileBytes; 



         String insertstring2 = @"Insert INTO Cert (CertName, CertLogo) 
                 values(@CertName, @CertLogo)"; 

         SqlCommand cmd3 = new SqlCommand("insertstring2", conn); 
         cmd3.CommandText = insertstring2; 
         cmd3.CommandType = CommandType.Text; 

         cmd3.Parameters.AddWithValue("@CertName", TextBox18.Text); 
         cmd3.Parameters.Add("@CertLogo", SqlDbType.VarBinary).Value = productImage; 

         cmd3.ExecuteNonQuery(); 
        } 
       } 
      } 

      catch (System.Data.SqlClient.SqlException ex) 
      { 

       string msg = "Insert Error:"; 
       msg += ex.Message; 
       throw new Exception(msg); 
      } 

      finally 
      { 
       Session.Abandon(); 
       conn.Close(); 
      } 

     } 
     protected void Button1_Click(object sender, EventArgs e) 
     { 


      InsertInfo(); 
      MultiView1.ActiveViewIndex += 1; 

     } 
protected void Button2_Click(object sender, EventArgs e) 
     { 
      MultiView1.ActiveViewIndex -= 1; 
     } 

     protected void Button5_Click(object sender, EventArgs e) 
     { 
      Response.Write("Successful"); 
     } 



    } 
} 
+0

Je ne suis pas en mesure d'ajouter des codes, il dit ident 4 espaces que je ne comprends pas. Alors j'ai posté le lien où j'ai posté une question dans le forum asp.Merci, – Girish

+0

Lorsque vous modifiez le poste, sélectionnez simplement le code et cliquez sur le bouton _ {} _ sur la barre d'outils – Jupaol

+0

Ok merci, j'ai posté mon code .. S'il vous plaît vérifier .. :) – Girish

Répondre

0

Le principal problème que vous allez avoir ici est que, comme il est écrit, vous ne fournissez pas le nombre correct de paramètres sur l'insert requête pour les première ou deuxième vues.

Quelques indications générales qui peuvent aider vous-

  • Utiliser switch/case plutôt que if/else if/else si le modèle si vous comparez toujours la même valeur, voir http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx
  • Utilisez toujours des accolades Pour if, même s'il s'agit d'une seule ligne, cela vous aide à analyser votre code visuellement et à comprendre la structure.
  • cmd.CommandType = CommandType.Text n'est pas nécessaire car cela est la valeur par défaut, mais vous pouvez l'inclure si vous sentez qu'il améliore la lisibilité
  • Ne pas mettre entre guillemets insertString dans SqlCommand cmd = new SqlCommand ("insertstring", conn) - à la place de la chaîne de caractères insertstring que vous avez déjà créée, l'utilisation de guillemets laisserait littéralement votre commande SQL "insertstring".
  • Si vous avez fourni la commande SQL en tant qu'argument (c'est-à-dire l'insertstring ci-dessus), vous n'avez pas besoin d'ajouter cmd.CommandText = insertstring;
  • Utilisez des identifiants significatifs dans votre code, que détient TextBox9 par exemple? Quelle est la fonction de Button2? Devoir aller chercher ça rendra le code difficile à maintenir et à mettre à jour.
  • Assurez-vous que vous étiquetez vos zones de texte dans le frontal en utilisant le contrôle asp: Label avec l'AssociatedControlID défini sur l'ID TextBox.
  • Assurez-vous validez que votre entrée d'utilisateur requis est fourni (validateurs sur le terrain d'utilisation nécessaire) et du type et de la longueur requise (définissez MaxLength sur la zone de texte contrôle pour correspondre à la longueur du champ dans la base de données)

Je suppose que votre code d'extrémité avant est quelque chose comme-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="EmployeeMultiView.AdminPages._Default" %> 

<!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></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
     <asp:MultiView ID="MultiView1" runat="server"> 
      <asp:View runat="server"> 
       <asp:Label AssociatedControlID="TextBox1" runat="server" Text="Label Text for TextBox1"></asp:Label> 
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox2" runat="server" Text="Label Text for TextBox2"></asp:Label> 
       <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox3" runat="server" Text="Label Text for TextBox3"></asp:Label> 
       <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox4" runat="server" Text="Label Text for TextBox4"></asp:Label> 
       <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox5" runat="server" Text="Label Text for TextBox5"></asp:Label> 
       <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox6" runat="server" Text="Label Text for TextBox6"></asp:Label> 
       <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox7" runat="server" Text="Label Text for TextBox7"></asp:Label> 
       <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox8" runat="server" Text="Label Text for TextBox8"></asp:Label> 
       <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox9" runat="server" Text="Label Text for TextBox9"></asp:Label> 
       <asp:TextBox ID="TextBox9" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox10" runat="server" Text="Label Text for TextBox10"></asp:Label> 
       <asp:TextBox ID="TextBox10" runat="server"></asp:TextBox> 
      </asp:View> 
      <asp:View runat="server"> 
       <asp:Label AssociatedControlID="TextBox11" runat="server" Text="Label Text for TextBox11"></asp:Label> 
       <asp:TextBox ID="TextBox11" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox12" runat="server" Text="Label Text for TextBox12"></asp:Label> 
       <asp:TextBox ID="TextBox12" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox13" runat="server" Text="Label Text for TextBox13"></asp:Label> 
       <asp:TextBox ID="TextBox13" runat="server"></asp:TextBox> 
       <asp:Label AssociatedControlID="TextBox16" runat="server" Text="Label Text for TextBox16"></asp:Label> 
       <asp:TextBox ID="TextBox16" runat="server"></asp:TextBox> 
      </asp:View> 
      <asp:View runat="server"> 
       <asp:Label AssociatedControlID="FileUpload1" runat="server" Text="Label Text for FileUpload1"></asp:Label> 
       <asp:FileUpload ID="FileUpload1" runat="server" /> 
       <asp:Label AssociatedControlID="TextBox18" runat="server" Text="Label Text for TextBox18"></asp:Label> 
       <asp:TextBox ID="TextBox18" runat="server"></asp:TextBox> 
      </asp:View> 
     </asp:MultiView> 

     <asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Next" /> 
     <asp:Button ID="Button2" OnClick="Button2_Click" runat="server" Text="Previous" /> 
    </div> 
    </form> 
</body> 
</html> 

Dans ce cas, je voudrais écrire votre code derrière comme this-

using System; 
using System.Data.SqlClient; 
using System.Data; 

namespace EmployeeMultiView.AdminPages 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!Page.IsPostBack) 
      { 
       MultiView1.ActiveViewIndex = 0; //Even though you don't need braces here it helps readability 
      } 
     } 

     private void InsertInfo() 
     { 
      String KKSTechConnectionString = @"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True"; 
      //Store connection strings in your web.config file wherever possible 

      //Session["sessFirstName"] = Request["textbox1"]; 

      try 
      { 
       //Move connection so we don't open it unless we have to 
       string insertstring = @"Insert INTO Emp (EmpID,FirstName,LastName,MiddleName,Mob1,Mob2,Phone,Email1,Email2,EmpDesc,Accno,IFSCCode,Branch,ApproxUnitPrice) 
       values (@EmpID,@FirstName,@LastName,@MiddleName,@Mob1,@Mob2,@Phone,@Email1,@Email2,@EmpDesc,@Accno,@IFSCCode,@Branch,@ApproxUnitPrice)"; 

       //Use switch/case to compare multiple values (see http://msdn.microsoft.com/en-us/library/vstudio/06tc147t.aspx) 
       switch (MultiView1.ActiveViewIndex) 
       { 
        case 0: 
         //Need all the SQL parameters so we don't try to insert to the database here 
         break; 
        case 1: 
         using (SqlConnection conn = new SqlConnection(KKSTechConnectionString)) 
         { 
          SqlCommand cmd = new SqlCommand(insertstring, conn); 
          //cmd2.CommandText = insertstring; - also redundent 
          //cmd2.CommandType = CommandType.Text; - this is the default value so not needed 

          //Add the parameters from the first view here, these will rely on ViewState which must be enabled 
          cmd.Parameters.AddWithValue("@EmpID", TextBox1.Text); 
          cmd.Parameters.AddWithValue("@FirstName", TextBox2.Text); 
          cmd.Parameters.AddWithValue("@LastName", TextBox3.Text); 
          cmd.Parameters.AddWithValue("@MiddleName", TextBox4.Text); 
          cmd.Parameters.AddWithValue("@Mob1", TextBox5.Text); 
          cmd.Parameters.AddWithValue("@Mob2", TextBox6.Text); 
          cmd.Parameters.AddWithValue("@Phone", TextBox7.Text); 
          cmd.Parameters.AddWithValue("@Email1", TextBox8.Text); 
          cmd.Parameters.AddWithValue("@Email2", TextBox9.Text); 
          cmd.Parameters.AddWithValue("@EmpDesc", TextBox10.Text); 

          cmd.Parameters.AddWithValue("@Accno", TextBox11.Text); 
          cmd.Parameters.AddWithValue("@IFSCCode", TextBox12.Text); 
          cmd.Parameters.AddWithValue("@Branch", TextBox13.Text); 
          cmd.Parameters.AddWithValue("@ApproxUnitPrice", TextBox16.Text); 

          conn.Open(); 
          cmd.ExecuteNonQuery(); 
         } 
         break; 
        case 2: 

         if (FileUpload1.HasFile) 
         { 
          byte[] productImage = FileUpload1.FileBytes; 

          String insertstring2 = @"Insert INTO Cert (CertName, CertLogo) 
                values(@CertName, @CertLogo)"; 

          using (SqlConnection conn = new SqlConnection(KKSTechConnectionString)) 
          { 
           SqlCommand cmd3 = new SqlCommand(insertstring2, conn); //No quotes 
           //cmd3.CommandText = insertstring2; - Redundant 
           //cmd3.CommandType = CommandType.Text; - this is the default value so not needed 

           cmd3.Parameters.AddWithValue("@CertName", TextBox18.Text); 
           cmd3.Parameters.Add("@CertLogo", SqlDbType.VarBinary).Value = productImage; 

           conn.Open(); 
           cmd3.ExecuteNonQuery(); 
          } 
         } 
         break; 
       } 
      } 
      catch (SqlException ex) 
      { 
       string msg = "Insert Error:"; 
       msg += ex.Message; 
       throw new Exception(msg); 
      } 
      finally 
      { 
       //Session.Abandon(); - this would run multiple times during the process 
      } 
     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      InsertInfo(); 
      //Don't try to set active view index to non-existant view 
      if (MultiView1.ActiveViewIndex < MultiView1.Views.Count) 
      { 
       MultiView1.ActiveViewIndex += 1; 
      } 
     } 

     protected void Button2_Click(object sender, EventArgs e) 
     { 
      //Assuming this is a "previous button" - may not need conditional if this is in the second view 
      if (MultiView1.ActiveViewIndex > 0) 
      { 
       MultiView1.ActiveViewIndex -= 1; 
      } 
     } 

     protected void Button5_Click(object sender, EventArgs e) 
     { 
      Response.Write("Successful"); 
      Session.Abandon(); //Move to end of operation 
     } 
    } 
} 
Questions connexes