我的C#代码有问题,我无法解决问题。所以,我的问题是我尝试登录时遇到异常。没有任何固定的元素对象。代码中的问题在哪里?例外:
指数超出允许范围。参数:index
代码:
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;
}
}
}
答案 0 :(得分: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
。