为什么我会遇到错误:索引超出了阵列的界限。 [英] Why I Am Getting Error : Index Was Outside The Bounds Of The Array.

查看:159
本文介绍了为什么我会遇到错误:索引超出了阵列的界限。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我的代码有问题,我不知道如何解决这个问题。

我的错误是索引超出了界限数组。当我在文本框中传递1或2个值时,它会出错,当我在文本框中传递3个或3个以上的值时它工作正常,所以请帮助我并解决我的问题,如果有人可以的话。



我的代码是

Hi
There is a problem in my code and i am not aware how to resolve this .
My Error is Index was outside the bounds of the array. when i am passing 1 or 2 value in textbox it gives error and when i am passing 3 or more than 3 value in textbox it is working fine so please help me and resolve my problem if anybody can .

My Code is

protected void btnsearch_Click(object sender, EventArgs e)
{
try
{
string shortWord = txtsearch.Text;
//split the text Into Seperate Words
string delimstr = ",";
char[] delimiter = delimstr.ToCharArray();
string[] ValueArray = shortWord.Split(delimiter);
SqlCommand cmd = new SqlCommand("select * from Rgisterbasic where name like '%" + ValueArray[0].Trim() + "%' and city like '%" + ValueArray[1].Trim() + "%' and email like '%" + ValueArray[2].Trim() + "%'", con);

SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}







谢谢

Gopal




Thanks
Gopal

推荐答案

原因是 shortWord.Split(分隔符); 是返回数组,当你调用<$ c时$ c> ValueArray [2] 它将获得结果数组中的第3项。如果您在阵列中少于3件物品,您将获得例外。



您可以在继续之前添加验证



reason is shortWord.Split(delimiter); is return array, when you call ValueArray[2] it will get the 3rd item in the result array. you will get exception you have less than 3 items in the array.

you can add validation before proceed

string[] ValueArray = shortWord.Split(delimiter);
if(ValueArray.Length<3)
{
   // show error message to user 
}else
{
   //select data from database
}


由于您访问 ValueArray 元素,请确保 ValueArray 在索引0,1处有三个元素2.

如果其中任何一个不存在,您将收到错误。
Since you are access ValueArray elements, ensure ValueArray has three elements at indexes 0,1 and 2.
If any one of these does not exist, you will get the error.


这篇关于为什么我会遇到错误:索引超出了阵列的界限。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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