索引超出范围。必须为非负数且小于集合的大小。参数名称:使用Sqldatareader 取数据时的索引
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index while fetch data using Sqldatareader
目前我在尝试使用 SqlDataReader 获取数据时遇到错误
并且参数在列表中,即 newcmd.Parameters.Add("@frmcat", res[i]);
这是我的代码
SqlDataAdapter adpt = new SqlDataAdapter("SELECT DISTINCT TOP 5 category, COUNT(category) AS totcom FROM coupon_deal WHERE (company LIKE '%" + query + "%') GROUP BY category ORDER BY totcom DESC", conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
int TotalRow = dt.Rows.Count;
List<string> res = new List<string>();
for (int i = 0; i < TotalRow; i++)
{
res.Add(dt.Rows[i]["category"].ToString());
}
List<string> cl = new List<string>();
SqlCommand newcmd = new SqlCommand("SELECT company, count(company) AS totcomp from coupon_deal Where (category LIKE @frmcat) GROUP BY company ORDER BY totcomp DESC", conn);
for (int i = 0; i <= res.Count; i++)
{
newcmd.Parameters.Clear();
newcmd.Parameters.Add("@frmcat", res[i]);
SqlDataReader sdr = newcmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
cl.Add(sdr["company"].ToString());
}
}
sdr.Close();
sdr.Dispose();
}
所以我 < res.Count 应该解决问题:
for (int i = 0; i < res.Count; i++)
{
newcmd.Parameters.Clear();
newcmd.Parameters.Add("@frmcat", res[i]);
SqlDataReader sdr = newcmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
cl.Add(sdr["company"].ToString());
}
}
sdr.Close();
sdr.Dispose();
}
目前我在尝试使用 SqlDataReader 获取数据时遇到错误 并且参数在列表中,即 newcmd.Parameters.Add("@frmcat", res[i]);
这是我的代码
SqlDataAdapter adpt = new SqlDataAdapter("SELECT DISTINCT TOP 5 category, COUNT(category) AS totcom FROM coupon_deal WHERE (company LIKE '%" + query + "%') GROUP BY category ORDER BY totcom DESC", conn);
DataTable dt = new DataTable();
adpt.Fill(dt);
int TotalRow = dt.Rows.Count;
List<string> res = new List<string>();
for (int i = 0; i < TotalRow; i++)
{
res.Add(dt.Rows[i]["category"].ToString());
}
List<string> cl = new List<string>();
SqlCommand newcmd = new SqlCommand("SELECT company, count(company) AS totcomp from coupon_deal Where (category LIKE @frmcat) GROUP BY company ORDER BY totcomp DESC", conn);
for (int i = 0; i <= res.Count; i++)
{
newcmd.Parameters.Clear();
newcmd.Parameters.Add("@frmcat", res[i]);
SqlDataReader sdr = newcmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
cl.Add(sdr["company"].ToString());
}
}
sdr.Close();
sdr.Dispose();
}
所以我 < res.Count 应该解决问题:
for (int i = 0; i < res.Count; i++)
{
newcmd.Parameters.Clear();
newcmd.Parameters.Add("@frmcat", res[i]);
SqlDataReader sdr = newcmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
cl.Add(sdr["company"].ToString());
}
}
sdr.Close();
sdr.Dispose();
}