2016-08-04 3 views
0

이것은 매우 이상한 질문이며, 질문에 포함 된 방대한 양의 코드에 사과드립니다.하지만 다른 사람의 프로젝트를 유지 관리하고 사용자가 나와 함께 왔습니다. 오류. 아래 보이는 InputBox를 여는 버튼이 있습니다.Visual Basic InputBox closing error

enter image description here

양식은 가져올 파일의 경로를 입력하는 데 사용됩니다. 사용자가 경로를 입력하지 않거나 잘못된 경로를 입력하면 오류가 표시됩니다. 이제 문제는 사용자가 'Cancel'버튼이나 오른쪽 상단의 x를 눌러 양식을 닫으면 경로를 찾을 수 없다는 동일한 오류를 반환한다는 것입니다.

다음 코드를 살펴본 후에 x 또는 Cancel을 누르면 오류가 표시되지 않도록 설정하는 방법을 배울 수 없으므로 아무도 나를 도와 줄 수 없습니까?

Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click 

    Try 
     Dim importbox As String = InputBox("Input path", "Import", "") 
     Dim fi As New FileInfo(importbox) 
     Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName 

     Dim conn As New OleDbConnection(connectionString) 
     conn.Open() 

     Dim add1 As String = "" 
     Dim add2 As String = "" 
     Dim add3 As String = "" 
     Dim add4 As String = "" 
     Dim add5 As String = "" 
     Dim postcode As String = "" 
     Dim telephone As String = "" 
     Dim fax As String = "" 
     Dim email As String = "" 
     Dim customercode As String = "" 
     Dim customername As String = "" 
     Dim webpage As String = "" 
     Dim mobile As String = "" 

     Dim headerTable As DataTable = ugHeaders.DataSource 
     Dim csvArray(headerTable.Rows.Count) As String 
     Dim i As Integer = 0 
     For Each dr As DataRow In headerTable.Rows 
      csvArray(i) = dr.Item("CSVName") 
     Next 

     For Each dr As DataRow In headerTable.Rows 
      Select Case dr.Item("DBName").ToString.Trim 
       Case "Add1" 
        add1 = dr.Item("CSVName") 
       Case "Add2" 
        add2 = dr.Item("CSVName") 
       Case "Add3" 
        add3 = dr.Item("CSVName") 
       Case "Add4" 
        add4 = dr.Item("CSVName") 
       Case "Add5" 
        add5 = dr.Item("CSVName") 
       Case "PostCode" 
        postcode = dr.Item("CSVName") 
       Case "Telephone" 
        telephone = dr.Item("CSVName") 
       Case "Fax" 
        fax = dr.Item("CSVName") 
       Case "Email" 
        email = dr.Item("CSVName") 
       Case "Customer_Name" 
        customername = dr.Item("CSVName") 
       Case "Customer_Code" 
        customercode = dr.Item("CSVName") 
       Case "webpage" 
        webpage = dr.Item("CSVName") 
       Case "mobile_phone" 
        mobile = dr.Item("CSVName") 
      End Select 
     Next 

     Dim sqlSelect As String = "SELECT Company, [" & add1 & "], [" & add3 & "], [" & postcode & "], [" & add2 & "], " & _ 
              "[" & telephone & "], [" & fax & "], [" & email & "], [" & customercode & "], " & _ 
              "[" & add4 & "], [" & add5 & "], [" & webpage & "], [" & mobile & "] FROM " & fi.Name 

     Dim cmdSelect As New OleDbCommand(sqlSelect, conn) 

     Dim adapter1 As New OleDbDataAdapter(cmdSelect) 

     Dim ds As New DataSet 
     adapter1.Fill(ds, "DATA") 

     pb_progress.Maximum = ds.Tables(0).Rows.Count 
     pb_progress.Value = 0 

     For Each dr As DataRow In ds.Tables(0).Rows 
      Try 
       Debug.WriteLine(dr.Item(customercode).ToString.Trim) 

       If dr.Item(customercode).ToString.Trim = "" Then 
        Dim str As String = dr.Item(customername) 
        If str.Trim = "" Then Continue For 
        Dim length As Integer = str.Length 
        If length < 20 Then 
        Else 
         length = 20 
        End If 

        str = Replace(str.Substring(0, length), " ", "_").ToUpper 
        str = Regex.Replace(str, "[^a-zA-Z _&]", "") 

        Dim found As Boolean = True 
        Dim loopcount As Integer = 1 

        Do Until found = False 
         Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = @ccode" 
         Dim checkCmd As New OleDb.OleDbCommand(checkSql, con) 
         checkCmd.Parameters.AddWithValue("@ccode", str) 
         Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd) 
         Dim checkDt As New DataTable 
         checkDa.Fill(checkDt) 

         If checkDt.Rows.Count <> 0 Then 
          found = True 
          str &= CStr(loopcount) 
          loopcount += 1 
         Else 
          found = False 
         End If 
        Loop 

        dr.Item(customercode) = str 
       Else 
        Dim found As Boolean = True 
        Dim loopcount As Integer = 1 
        Do Until found = False 
         Dim checkSql As String = "SELECT * FROM Customers WHERE [Customer_Code] = @ccode" 
         Dim checkCmd As New OleDb.OleDbCommand(checkSql, con) 
         checkCmd.Parameters.AddWithValue("@ccode", dr.Item(customercode)) 
         Dim checkDa As New OleDb.OleDbDataAdapter(checkCmd) 
         Dim checkDt As New DataTable 
         checkDa.Fill(checkDt) 

         If checkDt.Rows.Count <> 0 Then 
          found = True 
          dr.Item(customercode) &= CStr(loopcount) 
          loopcount += 1 
         Else 
          found = False 
         End If 
        Loop 
       End If 

       Dim sql As String 
       sql = "INSERT INTO Customers(Customer_Code, Customer_Name, Contract_Payment_Terms, Aq_Date, Telephone, Fax, Email, Average_Payment_Terms, webpage, mobile_phone) " & _ 
        "VALUES(@ccode, @cname, 30, #01/01/2016#, @ctele, @cfax, @email, 30, @webpage, @mobile);" 
       Dim cmd As New OleDb.OleDbCommand(sql, con) 
       With cmd.Parameters 
        .AddWithValue("@ccode", dr.Item(customercode)) 
        .AddWithValue("@cname", dr.Item(customername)) 
        .AddWithValue("@ctele", dr.Item(telephone).ToString.Truncate(48)) 
        .AddWithValue("@cfax", dr.Item(fax)) 
        .AddWithValue("@email", dr.Item(email)) 
        .AddWithValue("@webpage", dr.Item(webpage)) 
        .AddWithValue("@mobile", dr.Item(mobile)) 
       End With 
       cmd.ExecuteNonQuery() 

       sql = "INSERT INTO [Customer_Addresses] (Cust_Code, PostCode, Alias, Add1, Add2, Add3, Add4, Add5) VALUES(@ccode, @pcode, 'Default'" & _ 
        ",@add1, @add2, @add3, @add4, @add5);" 
       cmd = New OleDb.OleDbCommand(sql, con) 
       With cmd.Parameters 
        .AddWithValue("@ccode", dr.Item(customercode)) 
        .AddWithValue("@pcdoe", dr.Item(postcode)) 
        .AddWithValue("@add1", dr.Item(add1)) 
        .AddWithValue("@add2", dr.Item(add2)) 
        .AddWithValue("@add3", dr.Item(add3)) 
        .AddWithValue("@add4", dr.Item(add4)) 
        .AddWithValue("@add5", dr.Item(add5)) 
       End With 
       cmd.ExecuteNonQuery() 

      Catch ex As Exception 
       Debug.WriteLine(ex.Message) 
      End Try 


      pb_progress.Increment(1) 
     Next 

     MsgBox("Import successful", MsgBoxStyle.OkOnly, "Success") 

    Catch ex As Exception 
     errorLog(ex) 
    End Try 
End Sub 
+2

안녕하세요,이입니다. 다음과 같이 입력을 확인해야합니다 : Dim importbox As String = InputBox ("입력 경로", "가져 오기", ")'그리고 나서 If String.IsNullOrEmpty (importbox) 그러면 '취소되었거나 비어 있습니다' – pLurchi

+1

Inputbox는 항상 String을 반환합니다. 사용자가 "OK"를 누르면 TextBox에 입력 된 문자열을 반환합니다. X 또는 Cancel을 눌러 상자를 취소하면 ""을 반환합니다. – Luke

+0

[VisualBasic InputBox Cancel] 가능한 중복 (http://stackoverflow.com/questions/19679489/visualbasic-inputbox-cancel) – Luke

답변

2

Inputbox는 항상 returnString.

  • 사용자가 "확인"을 누르면 TextBox에 넣은 String을 반환합니다.
  • 그가 X를 눌러 상자를 취소하거나 취소하면 returns "".

일반적으로 파일 경로를 가져 오는 데 Inputbox를 사용하지 않는 것이 좋습니다. 대신 OpenFileDialog을 사용하십시오. 전체 경로가 이미 Clipboard에있는 경우 OFDFilename-Textbox에 붙여 넣기를하고 Enter 키를 누릅니다.

이것은 당신이 시작할 수 있어야 다음에서 InputBox 더 close 이벤트가 없기 때문에

Dim ofd as new OpenFileDialog() 
// Show the File Dialog to the user and detect he pressed OK or Cancelled 
if ofd.ShowDialog = Windows.Forms.DialogResult.OK 
     // Always check, if the file really exists 
     if IO.File.exists(ofd.FileName) 
     importbox = ofd.FileName 
     Else 
     msgbox("File does not exist") 
     Exit Sub 
     End if 
Else 
    Exit Sub 
End if 
+0

그래서 모든 코드를 질문에 그대로 두 겠지만 위에 추가하십시오. (어떤 버튼이 눌러 졌는지 확인하는 것 외에) – David

+0

Dim importbox As String = InputBox ("입력 경로", "가져 오기", "")를'Dim importbox as '로 바꾸면됩니다. String'을 입력 한 다음 코드를 답안의 다음 줄에 넣으십시오. 그것은 이미 트릭을해야합니다. 코드를 테스트하지 않았지만 내부에 오류가있는 경우이를 수정할 수 있습니다. – Luke