[英]Getting an error “IndexOutOfRangeExceptionwasunhandled” on MVC4 Resp API
i am new in c#, and making a Restful API on MVC4, i am using following code and gets an error on 我是C#的新手,并且在MVC4上创建了Restful API,我正在使用以下代码,并在
" foreach (DataRow menuDR in menuDataSet.Tables [7].Rows)"
IndexOutOfRangeException was unhandled by user code, and in details in show "cannot find table7" i used the same approach with 1 table database 用户代码未处理IndexOutOfRangeException,在显示“找不到表7”中的详细信息中,我对1个表数据库使用了相同的方法
foreach (DataRow menuDR in menuDataSet.Tables [0].Rows)
and it was working,now i have 8 tables in database, i don't know how to handle this exception and tried various things to get it sort.... 它正在工作,现在我数据库中有8个表,我不知道如何处理该异常,并尝试了各种方法来对它进行排序。
public IEnumerable<RestaurantsMenu> GetAllMenu()
{
menuCon = new SqlConnection ("Data Source=MyPc\\MyPc;Initial Catalog=MENU;Integrated Security=True");
menuDataAdapter = new SqlDataAdapter (" SELECT * FROM RestaurantsMenu ", menuCon);
foreach (DataRow menuDR in menuDataSet.Tables [7].Rows)
{
Rst_Menu.Add(new RestaurantsMenu(){Restaurant_ID = int .Parse (menuDR[0].ToString()), RestaurantName =menuDR[1].ToString(),
Menu =menuDR[2].ToString(), Price=int .Parse (menuDR[3].ToString()) } );
}
return Rst_Menu;
}
Problem : you are querying only single table (table index 0) data from Database and trying to access table with index 7 which is not available. 问题:您仅从数据库中查询单个表(表索引0)的数据,并尝试访问索引7(不可用)的表。
even though there are 8 tables in your database following query does not give you all 8 tables data which will only give you the table data with index zero. 即使您的数据库中有8个表,以下查询也不会给您全部8个表数据,而这只会给您索引为零的表数据。
SELECT * FROM RestaurantsMenu
Solution : with the above select
statement you should always referto Tables[0]
as you get only single table. 解决方案:使用上面的select
语句,您应该始终引用Tables[0]
因为您仅获得单个表。
Try This: to get mutiple tables 试试这个:获取多个表
SqlDataAdapter menuDataAdapter = new SqlDataAdapter("SELECT * FROM RestaurantsMenu1; "SELECT * FROM RestaurantsMenu2;"SELECT * FROM RestaurantsMenu3;", connection);
menuDataAdapter.TableMappings.Add("Table1", "RestaurantsMenu1");
menuDataAdapter.TableMappings.Add("Table2", "RestaurantsMenu2");
menuDataAdapter.TableMappings.Add("Table3", "RestaurantsMenu3");
for(int i=0;i<menuDataSet.Tables.Count;i++)
{
foreach (DataRow menuDR in menuDataSet.Tables[i].Rows)
{
Rst_Menu.Add(new RestaurantsMenu(){Restaurant_ID = int .Parse (menuDR[0].ToString()), RestaurantName =menuDR[1].ToString(),
Menu =menuDR[2].ToString(), Price=int .Parse (menuDR[3].ToString()) } );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.