我很想读取数据库输出并且字段在数据库中但是它给了我IndexoutofRangeException错误。我声明BLabel就像数据库中的其他值一样。有什么建议吗?
SqlConnection dbConn = null;
StringBuilder sqlString = new StringBuilder();
sqlString.Append("SELECT f.*, v.VersionNumber ");
sqlString.Append("FROM PackLabelFormat f, PackLabelVersion v ");
sqlString.Append(" WHERE f.FormatID = @FormatID ");
sqlString.Append(" AND f.FormatID = v.FormatID ");
sqlString.Append(" AND v.VersionID = (SELECT MAX(VersionID) ");
sqlString.Append("FROM PackLabelVersion v2 ");
sqlString.Append("WHERE v2.FormatID = v.FormatID) ");
try
{
using (dbConn = new SqlConnection(Properties.Settings.Default["tville"].ToString()))
{
SqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = sqlString.ToString();
cmd.Parameters.AddWithValue("@FormatID", FormatID);
dbConn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
FormatName = reader["FormatName"].ToString();
FormatDescription = reader["FormatDescription"].ToString();
StockID = Convert.ToInt32(reader["StockID"].ToString());
PrintCode = bool.Parse(reader["PrintPlantCode"].ToString());
PrintPrice = bool.Parse(reader["PrintPrice"].ToString());
PrintWeight = bool.Parse(reader["PrintWeight"].ToString());
CurrentVersion = reader["VersionNumber"].ToString();
BLabel = bool.Parse(reader["BSupported"].ToString());
LLabel = bool.Parse(reader["LSupported"].ToString());
}
else
{
throw new Exception("No LabelFormat found for ID " + this.FormatID.ToString());
}
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); }
catch { }
}
}
答案 0 :(得分:-1)
造成IndexoutofRangeException的原因是我的查询只查找v.VersionNumber而不是我试图检索的所有值,例如BLabel和LLabel。