2015-05-13 3 views
0

В настоящее время я получаю эту ошибку: 'System.Data.SqlClient.SqlException' на этой линии:'System.Data.SqlClient.SqlException'

int MemberExist = (int)check_Member.ExecuteScalar(); 

Вот мое исключение: http://imgur.com/bnp7OcT

I пытаюсь открыть соединение с базой данных и извлечь данные из текстового поля и посмотреть, совпадает ли идентификатор с именем и фамилией в базе данных. Если это так, то продолжает выполнение кода, который записывается в файл PDF, и если он не вводит определенный код из текстовых полей в базу данных. Я уверен, что в моем коде есть и другие ошибки, и было бы здорово, если бы кто-то мог помочь с этим, но в настоящее время я только прошу помощи об ошибке выше, вот что у меня есть до сих пор:

 protected void btnSubmit_Click(object sender, EventArgs e) 
     { 


      string PostCode = txtPostcode.Text; 
      string PostCode2 = txtDestinationPostcode.Text; 

      // Get the connection 
      SqlConnection DBConnection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=""E:\DS\Prac5\Part1\App_Data\MyDatabase.mdf"";Integrated Security=True"); 
      SqlDataReader Reader = null; 



      DBConnection.Open(); 
      SqlCommand check_Member = new SqlCommand("SELECT * FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput)", DBConnection); 
      check_Member.Parameters.AddWithValue("@Txtnput", txtMembershipid.Text); 

      //THIS IS THE LINE BELOW I'm HAVING ISSUES WITH 

      int MemberExist = (int)check_Member.ExecuteScalar(); 

      if (MemberExist > 0) 
      { 
       // if Member exists 

       PostCodeInfo MatchingPostCode = Find(PostCodeList, PostCode); 
       if (MatchingPostCode == null) 
       { 
        lblOutput.Text = "Your postcode could not be found!"; 

       } 
       else 
       { 
        lblOutput.Text = string.Format("({0},{1})", MatchingPostCode.Locality, MatchingPostCode.State); 

       } 


       PostCodeInfo MatchingPostCode2 = Findtwo(PostCodeList, PostCode2); 
       if (MatchingPostCode2 == null) 
       { 
        lblOutput2.Text = "Your postcode could not be found!"; 

       } 
       else 
       { 
        lblOutput2.Text = string.Format("({0},{1})", MatchingPostCode2.Locality, MatchingPostCode2.State); 

       } 

       // Put Code here if member text = to member ID 
       // If not insert member into database 


       //We keep track of our invoice number by storing it in a plain text file. Using only a variable in memory means that it resets every time our web server turns off! 
       string NewInvoiceNumber = GenerateNextInvoiceNumber(InvoiceFilePath); 

       //Creating a document that will be stored on the web server's hard drive 
       Document MyDoc = new Document(); 
       string PDFPath = Server.MapPath("PDFs"); 
       //Name each of our PDF files uniquely using the invoice number so we don't overwrite them. 
       FileStream LocalStream = new FileStream(string.Format(@"{0}\Receipt-{1}.pdf", PDFPath, NewInvoiceNumber), FileMode.Create); 
       PdfWriter.GetInstance(MyDoc, LocalStream); 

       //Also store the document in memory such that we can send it to the client as an array of bytes 
       MemoryStream HTTPStream = new MemoryStream(); 
       PdfWriter.GetInstance(MyDoc, HTTPStream); 

       //Creating the PDF 
       MyDoc.Open(); 
       //Create the custom fonts we'll use in the PDF 
       Font Blue = new Font(Font.FontFamily.TIMES_ROMAN, 20f, Font.NORMAL, new BaseColor(System.Drawing.Color.Blue)); 
       Font Grey = new Font(Font.FontFamily.TIMES_ROMAN, 12f, Font.NORMAL, new BaseColor(System.Drawing.Color.Gray)); 
       Font Black = new Font(Font.FontFamily.TIMES_ROMAN, 14f, Font.NORMAL, new BaseColor(System.Drawing.Color.Black)); 

       //We create our Title paragraph seperately because we need to specify the text alignment in order to put it in the center. 
       Paragraph Title = new Paragraph("Truck delivery receipt\n", Blue); 
       Title.Alignment = Element.ALIGN_CENTER; 
       MyDoc.Add(Title); 

       MyDoc.Add(new Paragraph(string.Format("\nProccessed on " + DateTime.Now.ToString("dd/MM/yyyy h:mm:tt."), Black))); 
       MyDoc.Add(new Paragraph(string.Format("\nThank you for doing business with Truck Deliveries Co., {0} {1}", txtName.Text, txtLastName.Text))); 
       MyDoc.Add(new Paragraph(string.Format("Your invoice number is {0}. ", NewInvoiceNumber, Black))); 
       MyDoc.Add(new Paragraph(string.Format("Please quote this number if you contact support.\n"))); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       Paragraph Heading = new Paragraph("Delivery details\n", Blue); 
       MyDoc.Add(Heading); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       MyDoc.Add(new Paragraph(string.Format("Your delivery will arrive at {0}, after leaving for delivery at {1} ", txtDeliveryDate.Text, DateTime.Now.ToString("dd/MM/yyyy h:mm:tt.")))); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       MyDoc.Add(new Paragraph(string.Format("{0} truck delivery from {1}, {2} {3} to {4}, {5} {6}.", txtNumberoftrucks.Text, txtDeliveryAddress.Text, txtPostcode.Text, lblOutput.Text, txtDestinationDeliveryAddress.Text, txtDestinationPostcode.Text, lblOutput2.Text))); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       MyDoc.Add(new Paragraph(string.Format("Cost of delivery:$19,830.00."))); 
       MyDoc.Add(new Paragraph(string.Format("Cost of insurance:$289.87."))); 
       MyDoc.Add(new Paragraph(string.Format("Cost charged (incl. GST):$22102.87. "))); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       MyDoc.Add(new Paragraph(string.Format("Any queries regarding your delivery can be sent to [email protected], or alternatively you can call 03 9876 5432."))); 
       MyDoc.Add(new Paragraph(string.Format("\n"))); 
       MyDoc.Add(new Paragraph(string.Format("Our business is located at 72 Kaolin Street, VIC, AU. The Fees from this truck delivery will be charged to {0}. We will contact you via the phone number 03 9876 1234 if we experience any issues with yourt order.", txtBillingAddress.Text))); 

       MyDoc.Add(new Paragraph(string.Format("\n"))); 

       MyDoc.Close(); 

       //Send PDF to client via a HTTP 
       Response.ContentType = "application/pdf"; 
       Response.AddHeader("Content-Disposition", string.Format(@"attachment; filename=Receipt-{0}.pdf", NewInvoiceNumber)); 
       Response.BinaryWrite(HTTPStream.ToArray()); 

      } 
      else 
      { 

       //Member doesn't exist. 
       string firstname = txtName.Text; 
       string lastname = txtLastName.Text; 
       string query = "INSERT INTO Wines(firstname, lastname) " + 
           "Values('" + firstname + "', '" + lastname + "')"; 

      } 
+0

Что такое сообщение в исключении? –

+0

Оберните вызов ExecuteScalar с помощью блока catch catch, который ловит SqlException, который должен предоставить вам дополнительную информацию о том, почему он не работает. – Steve

+2

Я готов поспорить, хотя эта часть вашего SQL: 'MembershipID = FirstName', я предполагаю, что MemberhipID должен быть целым числом, а FirstName не является входом и не может быть конвертирован в целое или экранирован как строка. –

ответ

1

У вас есть дополнительная скобка в конце вашего запроса, сразу после @Txtnput. Это должно быть:

 SqlCommand check_Member = new SqlCommand("SELECT * FROM Members WHERE MembershipID = FirstName AND LastName = @Txtnput", DBConnection); 
+0

Ах, замечательно спасибо! – user4814432

Смежные вопросы