我在这里研究了其他答案,但没有一个真的适合我的情况。我已经向数据库添加了一个表,现在我收到了这个错误。事情是,它在其他人的计算机上工作,但在我的,我收到以下错误。附:我的关系很好(如果你徘徊):
IndexOutOfRangeException
未被用户代码
An exception of type `System.IndexOutOfRangeException` occurred in System.Data.dll but was not handled in user code
Additional information: Cannot find table 0.
违规代码是for循环中int i = 0
的初始化
这是我的代码
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
string strSQLconnection = "Data Source=LOTUS;Initial Catalog=PMRS;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(strSQLconnection);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from PMRS.dbo.BOARDMEMBERS order by ORDERID";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConn;
SqlDataAdapter sa = new SqlDataAdapter();
try
{
sqlConn.Open();
sa.SelectCommand = cmd;
sa.Fill(ds);
int rCount = ds.Tables[0].Rows.Count;
}
catch (Exception ex)
{
Response.Write(ex);
sqlConn.Close();
sqlConn.Dispose();
}
finally
{
sqlConn.Close();
sqlConn.Dispose();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["ID"].ToString() != "2")
{
sb.Append("<div class=\" col-md-6 \">");
sb.Append("<img src=\"../images/board/" + ds.Tables[0].Rows[i]["IMAGE"].ToString() + "\" /> ");
sb.Append("<h3>" + ds.Tables[0].Rows[i]["TITLE"].ToString() + "</h3> ");
sb.Append("<h4>" + ds.Tables[0].Rows[i]["FNAME"].ToString() + " " + ds.Tables[0].Rows[i]["MI"].ToString() + " " + ds.Tables[0].Rows[i]["LNAME"].ToString() + "</h4>");
sb.Append("<p>" + ds.Tables[0].Rows[i]["BIO"].ToString() + "</p> ");
sb.Append("<p>" + ds.Tables[0].Rows[i]["SUFFIX_PREFIX"].ToString() + "</p> ");
sb.Append("</div>");
}
}
Literal1.Text = sb.ToString();
}
我是一名前台开发人员,在服务器端编程中再次弄湿手,这对我来说很容易。向宝宝解释一下。大声笑谢谢
答案 0 :(得分:3)
您收到错误是因为您尝试访问ds.Tables[0]
,但ds.Tables
没有任何元素。在访问ds.Tables
之前,您必须检查ds.Tables
是否为空且ds.Tables[0]
是否包含任何元素
StringBuilder sb = new StringBuilder();
if (ds.Tables != null && ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
....
}
Literal1.Text = sb.ToString();
}
else
{
// do something when ds.Tables is null or ds.Tables doesn't have any elements
}
答案 1 :(得分:1)
我不是关注结果集,而是查看你的连接字符串和包含在catch
块中的异常,因为很明显命令/适配器没有返回任何内容。那么,看一下连接字符串......
Data Source=LOTUS;Initial Catalog=PMRS;Integrated Security=True
并确保......
LOTUS
BOARDMEMBERS
表最后,看看这里的反应......
catch (Exception ex)
{
Response.Write(ex); //<------ check this out, there must be an exception bubbling up
sqlConn.Close();
sqlConn.Dispose();
}
检查此处是否发生异常...在finally
块之后注释掉所有内容,以便可以将异常(如果有)发送到响应...因为未处理的异常可能是用黄色屏幕覆盖了响应&#34; (如果您还没有设置自定义错误页面)
答案 2 :(得分:0)
您可能需要在运行命令时检查它是否已成功执行(例如,您是否使用数据库查询工具查看数据库并查看表是否存在?)
此外,您应该检查您的查询返回的内容并发布。也许它找不到任何结果?