如何修复outofrange异常/找不到列1.在MVC中 [英] How to fixed outofrange exception /cannot find column 1. In MVC

查看:77
本文介绍了如何修复outofrange异常/找不到列1.在MVC中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MVC视图中调用xml数据来显示它但得到异常错误。任何帮助将不胜感激。



我尝试过:



-------- XML ----

I am trying to call the xml data in MVC view to display it but get the exception error. Any help will be much appreciated.

What I have tried:

--------XML----

<root>
    <states>
        <state>
            <statename>Abia</statename>
            <stateid>101</stateid>
        </state> 
        <state>
            <statename>Adamawa</statename>
            <stateid>102</stateid>
        </state> 
        <state>
            <statename>Akwa Ibom</statename>
            <stateid>103</stateid>
        </state> 
        ...
    </states>
</root>





----- C#code ---



-----C# code---

public class XMLREADER
{
    public List<Products> ReturnListOfProducts()
    {
        string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductData.xml");//Path of the xml script  
        DataSet ds = new DataSet();//Using dataset to read xml file  
        ds.ReadXml(xmlData);
        
        var products = new List<Products>();
        products = (from rows in ds.Tables[0].AsEnumerable()
                    select new Products
                    {       
                        StateName = rows[0].ToString(),
                        StateId = Convert.ToInt32(rows[1].ToString()),
                    }).ToList();
        
        return products;
    }
}

推荐答案

调试代码并检查 DataSet 。您将看到第一个表只有一列 - states_Id 。您尝试阅读的数据位于第二个表格中。

Debug your code and examine the DataSet. You will see that the first table only has a single column - states_Id. The data you're trying to read is in the second table.
public List<Products> ReturnListOfProducts()
{
    string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/ProductData.xml");
    DataSet ds = new DataSet();
    ds.ReadXml(xmlData);
    
    return (from rows in ds.Tables[1].AsEnumerable()
            select new Products
            {       
                StateName = rows[0].ToString(),
                StateId = Convert.ToInt32(rows[1]),
            }).ToList();
}



您可以通过使用调试器更快地找到它。


You could have found this out for yourself much faster by using the debugger.


这篇关于如何修复outofrange异常/找不到列1.在MVC中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆