我的代码抛出System.IndexOutOfRangeException如何修复它? [英] My code is throwing System.IndexOutOfRangeException How to fix it?

查看:250
本文介绍了我的代码抛出System.IndexOutOfRangeException如何修复它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataRow[] Typliste = dsret.Select(String.Format("Label = '{0}'", strFeldnamen));
           
           try
           {
               Datentyp = "";
               Datentyp = Typliste[0].ItemArray[1].ToString();
           }
           catch
           {
               return false;
           }





然后抛出System.IndexOutOfRangeException如何修复它。



then its throwing System.IndexOutOfRangeException how to fix it.

推荐答案

足够简单。不要尝试使用不存在的索引,也不会出现错误。



你的代码是ASSUMING,它是数组中的项目而不是实际上就在那里。



要么Select不返回任何行,要么返回的代码少于你的代码所假设的结果。
Easy enough. Don't try and use an index that doesn't exist and you won't get the error.

Your code is ASSUMING that are more items in an array than actually are there.

Either the Select is not returning any rows or it's returning fewer columns than your code is assuming are in the results.


将元素数量存储到变量中,并使用它们来访问列表而不是硬编码值。

例如。

int numOfLabels = Typliste.Length();

和/或

if(numOfLabels> 0)

{

Datentyp = Typliste [0] .ItemArray [1] .ToString();

}
Store the number of elements into a variable and use those to access the list rather than hard coded values.
For example.
int numOfLabels = Typliste.Length();
and/or
if(numOfLabels > 0)
{
Datentyp = Typliste[0].ItemArray[1].ToString();
}


这篇关于我的代码抛出System.IndexOutOfRangeException如何修复它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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