如何解决索引超出Split String数组的范围

问题描述:

亲爱的所有人,

在我的问题代码下面给出了绑定网格。但问题是索引超出了数组的范围。

Dear All,
Given Below My Problem Code for bind Grid. But Problem is Index was outside the bounds of the array.

public void displayGridView()
{

string vori_80 = string.Empty;
while (sdr.Read())
{

string gf_80 = ConvertDBNull.To<string>(sdr["gift_80"], String.Empty);// Get string from read database for Split

string[] stringSeparators_80 = new string[] { "@@" };
var result_80_vori = gf_80.Split(stringSeparators_80, StringSplitOptions.None);// Split this string.
gift_80 = ConvertDBNull.To<string>(result_80_vori[0], String.Empty);// Here Problem Index was outside the bounds of the array
vori_80 = ConvertDBNull.To<string>(result_80_vori[1], string.Empty);
dt.Rows.Add(ops_id, comments, pname, cname, TARGET, SALES, type, thana, dist, division, Target_80, Total_AMT_80, gift_80, vori_80, Target_90, Total_AMT_90, Total_AMT_90, gift_90, vori_90, Target_100, Total_AMT_100,gift_100,vori_100, contact_person,cmobile,wifename,SP_NAME,ZI_NAME,RH_NAME,MG_NAME);

}
sdr.Close();
SqlCon.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}





N.B:某些行添加DataTable但Full Row不添加DataTable。显示错误是索引超出了数组的范围。拆分字符串的此错误。但无法解决这个问题。怎么能解决这个问题。



N.B: Some Row add with DataTable But Full Row don't add With DataTable. Show Error is Index was outside the bounds of the array. This error for split string. But Can not Solved this Problem. How can Solve this problem.


我想说我们必须从问题中退一步你要解决并看看另一个问题,你的编码风格会导致你的问题。



我想向你介绍两种编码范例:首先称为'早期失败',如果可以,则需要在代码时间预测你的代码无法继续的任何原因,你应该在那里停止它并以一种让程序员注意的方式使操作失败,这样才能解决这个逻辑缺陷发生的原因。

另一个是'防守代码'并且意味着如果你的代码中有任何变量有可能进入可能导致异常的状态,请先检查它并故意处理它,因为否则你会把它直接扔到这是一个包罗万象的错误处理程序,它不太清楚什么是正确的事情。



代码没有如果有任何数据违反,就像肆意抛出异常,但我怀疑这是问题(某些行有无效数据)好好看一下,应该在视图中弹出问题:

Hi Well i would say we have to take a step back from the problem You want to solve and look at another, your coding style is leading to your problems.

I would like to introduce 2 coding paradigms to you: First is called 'fail early' and entails that if you can predict at code time any reason why your code cannot continue, you should stop it there and fail the operation in a way that will make a programmer notice so the reason for that logical flaw to happen will be fixed.
The other is 'code defensively' and mean that if there is any chance of any variable in your code getting into a state that could cause an exception, check for that first and handle it intentionally, because othewise you'll throw it streight into the all encompassing error handler which has much less of a clue what would be the right thing to do.

The code doesn't have to be as draconical throwing exception if any data violates, but i suspect this is the problem (some row with invalid data) so well have a look, should pop the problem right out in view:
public void DisplayGridView(SqlDataReader sdr)
        {

            string vori_80 = "";
            while (sdr.Read())
            {
                var gf_80 = sdr["gift_80"] as string;
                if(string.IsNullOrEmpty(gf_80)) throw new Exception("No data supplied");

                const string seperator = "@@";
                if(!gf_80.Contains(seperator)) throw new Exception("There must be more than one value in this field");

                var result_80_vori = gf_80.Split("@@".ToCharArray());
                if (result_80_vori.Length < 2) throw new Exception("Data sould contain at least two values seperated by @@");

                object value = result_80_vori[0];
                var gift_80 = value == null ? "" : value.ToString();

                value = result_80_vori[1];
                vori_80 = value == null ? "" : value.ToString();

                //dt.Rows.Add(ops_id, comments, pname, cname, TARGET, SALES, type, thana, dist, division, Target_80, Total_AMT_80, gift_80, vori_80, Target_90, Total_AMT_90, Total_AMT_90, gift_90, vori_90, Target_100, Total_AMT_100, gift_100, vori_100, contact_person, cmobile, wifename, SP_NAME, ZI_NAME, RH_NAME, MG_NAME);
            }
            sdr.Close();
            //SqlCon.Close();
            //GridView1.DataSource = dt;
            //GridView1.DataBind();
        }





最后一个一条建议,在你的方法中停止使用全局变量,让多个代码点触及相同数据会让人感到困惑和危险。你向dt添加一行的行你有很多值出现在哪里,如果你传入一个以这些为参数的结构,那就更好了,你可能会注意到我转移到的datareader也是如此方法参数列表。

看来你有一些方法可以完全'吻'你的代码 http://en.wikipedia.org/wiki/KISS_principle [ ^ ]


if (gf_80.Contains("@@"))
          {
             //Do your stuff here.
          }