2014-10-17 26 views
-3

我的C#代碼有問題,我無法解決問題。所以,我的問題我嘗試登錄時遇到異常。沒有任何固定的元素對象。代碼中的問題在哪裏?例外情況:該指數超出允許範圍。爲什麼?

該指數超出允許範圍。參數:指數

代碼:

public dbresult.GetSome Get(Oneword.dbcon conn, string tablename) { 
     string constring = "Server=" + conn.Host + ";Database=" + conn.Database + ";Uid=" + conn.Username + ";Pwd=" + conn.Password; 
     int i,im=0; 

     Oneword.dbresult.GetSome result = new dbresult.GetSome(); 
     MySqlConnection connection = new MySqlConnection(constring); 

     connection.Open(); 

     try { 
      MySqlDataReader oszlopok_cmd = null; 
      MySqlDataReader sorok_cmd = null; 

      DataTable oszlopok = null; 

      MySqlCommand cmd = connection.CreateCommand(); 

      cmd.CommandText = "SELECT * FROM "+tablename; 

      // Oszlopok lekérése 
      oszlopok_cmd = cmd.ExecuteReader(CommandBehavior.SchemaOnly); 
      oszlopok = oszlopok_cmd.GetSchemaTable(); 
      oszlopok_cmd.Close(); 

      List<string> columns = new List<string>(); 
      foreach (DataRow col in oszlopok.Rows) { 
       columns.Add(col.Field<String>("ColumnName")); 
      } 

      // Sorok lekérése, és tárak feltöltése 
      sorok_cmd = cmd.ExecuteReader(); 

      while (sorok_cmd.Read()) { 
       i = result.AddNewDir(); 

       foreach (string clomone in columns) { 
        result.AddKeyValue(i, clomone, sorok_cmd.GetString(im)); 
        im++; 
       } 
      } 
     } 
     finally { 
      connection.Close(); 
     } 

     return result; 
    } 

public class dbresult { 
    public class GetSome { 
     private List<Dictionary<string, string>> dirlistem = new List<Dictionary<string, string>>(); 
     private int cuID = 0; 

     public void AddKeyValue(int dirID, string key, string value){ 
      dirlistem[dirID][key] = value; 
     } 
     public int AddNewDir() { 
      Dictionary<string,string> added = new Dictionary<string,string>(); 
      cuID++; 
      return cuID - 1; 
     } 
     public Dictionary<string, string> GetDir(int dirID) { 
      return dirlistem[dirID]; 
     } 
     public void ModifyValue(int dirID, string key, string value) { 
      dirlistem[dirID][key] = value; 
     } 

    } 
} 
+3

指定引發異常的行可能會非常有用......但是您是否嘗試過調試並查看該行上發生了什麼?聽起來就像你試圖找到那些不存在的東西。 – crashmstr 2014-10-17 20:01:44

+0

我會認爲這是排列的對象。你需要找到問題所在的線路。例外會告訴你。然後,您可以告訴我們是什麼對象導致錯誤,或者自己調試以找出錯誤發生的原因。 – deathismyfriend 2014-10-17 20:02:44

+0

connection.Close();或者當我插入catch {throw;投擲; – mbalint987 2014-10-17 20:03:23

回答

2

您不添加創建詞典列出:

public int AddNewDir() { 
    Dictionary<string,string> added = new Dictionary<string,string>(); 
    // *** 
    dirlistem.Add(added); 
    // *** 
    cuID++; 
    return cuID - 1; 
} 

因此,在這裏你有dirlistem[dirID]任何地方將拋出一個異常。

此外,您不需要cuID成員在GetSome類。只需

return dirlistem.Count - 1; 

AddNewDir