2011-09-29 18 views
0

嗨,我有一個登錄連接到服務器字符串,並在登錄按鈕被按下時執行此操作。如果用戶和密碼未存儲在數據庫中,它將返回無效錯誤,但如果它們位於數據庫上,則會引發「索引位於數組邊界外」錯誤。我將如何解決這個問題? 謝謝索引在c#上的數組錯誤的邊界外登錄使用SQL

我的連接字符串位於我的appconfig文件中,問題可以在那裏嗎?

########## Windows表單登錄後按一下按鈕
private void btnOK_Click(object sender, EventArgs e) 
{ 
SqlConnection con = Program.GetConnection; 
SqlDataReader dr = null; 
try 
    { 
      SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE UserName='" + 
      txtName.Text + "'AND Password='" + textpassword.Text + "'", con); 
      dr = cmd.ExecuteReader(); 
      if (dr.Read()) 
      { 
       Program.UserLoginName = dr.GetString(3); 
       this.Close(); 
      } 
      else 

       MessageBox.Show("Invalid Username & Password!"); 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
####### Program.cs的文件
Using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Windows.Forms; 
using System.Data.SqlClient; 
using System.Configuration; 

namespace FrontEndV1 
{ 
static class Program 
{ 
    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 
     Application.Run(new Login()); 
    } 
    public static SqlConnection GetConnection 
    { 
     get 
     { 
      string ConnectionString = ConfigurationManager.ConnectionStrings["FrontEndV1Connection"].ConnectionString; 
      SqlConnection con = new SqlConnection(ConnectionString); 
      con.Open(); 
      return con; 
     } 
    } 
    public static string UserLoginName { get; set; } 
} 

}

+0

-1未響應。 **用戶**表中有多少列? – adatapost

+3

@AVD:我認爲在這種情況下,這是不適合downvote用戶,它被視爲「18分鐘前」相應的SO統計。我相信你可以在相同的情況發佈問題和sidetracked一段時間,這不是一個downvote的原因 – sll

回答

1

我認爲這個錯誤在這裏:dr.GetString(3);嘗試將3改爲2.數組從數組開始。

1

這是你的問題:

Program.UserLoginName = dr.GetString(3); 

你會得到一個字段,其索引大於返回的字段數。
您必須使用介於0和dr.FieldCount-1之間的索引。

或者您可以使用dr.GetString(dr.GetOrdinal(desired_field_name)):這樣更好(即使它需要更多說明),因爲您可以交換返回訂單(也許您需要更改查詢)而不會丟失功能。

+0

而問題是.......因爲.....和解決方案是........ – Johan

+0

@Johan:你覺得現在好多了? :)謝謝 – Marco

+0

@stefan:看看我編輯過的文章 – Marco

0

我認爲你只有三列。第3列的索引是2,所以改變該線

Program.UserLoginName = dr.GetString(3);

Program.UserLoginName = dr.GetString(2);

1

你不說其中錯誤被拋出,但我懷疑這條線:如果查詢返回的任何超過4列少

Program.UserLoginName = dr.GetString(3); 

將拋出錯誤。

此外,這是易受Sql注入。使用存儲的proc或參數化查詢。

+0

或者使用LINQ2SQL –

0

你不能調試應用程序嗎?如果你能做到,那就試着找出引發異常的位置。正如Marco和其他用戶所建議的,如果在執行dr.GetString(3)時注意到異常,那麼問題就在於此。嘗試使用正確的列序號,或使用SELECT Column1, Column2, ..., ColumnN FROM Table,以便您確切知道要指定哪個序號。

0

壞的編碼:

  1. 使用select *,你應該使用使用索引來檢索連續值的列
  2. 的名字,你應該用實際的列名返回

如果上述應用將會沒有問題。

相關問題