索引不在Array的范围内 [英] Index was outside the bounds of Array

查看:127
本文介绍了索引不在Array的范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我的数据库中有一个表Company,我想读取其中code =''12345''
的名称 但是它显示异常,因为Index在Array的范围之外

我写的代码如下


SqlCommand cmd =新的SqlCommand();
SqlDataReader rdr = null;
conn.Open();
字符串str =从公司选择名称,其中CCode =" 12345";
cmd.CommandText = str;
cmd.Connection = conn;
rdr = cmd.ExecuteReader();
如果(rdr.Read())
{
System.Windows.MessageBox.Show("Test");

this.txtname.Text = rdr.GetString(2)


}

Hi,


I have a table Company in my database from that I want to read the name where the code=''12345''
but it shows exception as Index was outside the bound of Array

I wrote the code as follows


SqlCommand cmd = new SqlCommand();
SqlDataReader rdr = null;
conn.Open();
String str = "select name from Company where CCode=''12345''";
cmd.CommandText = str;
cmd.Connection = conn;
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
System.Windows.MessageBox.Show("Test");

this.txtname.Text = rdr.GetString(2)


}

推荐答案

LukmanulHakeem.T写道:
LukmanulHakeem.T wrote:

其中CCode




您已经使用了CCode.您是否需要使用代码?




You''ve used CCode. Do you need to use Code instead?


您只从查询中返回单个值,因此该行;
You are only returning a single value from your query therefore the line;
this.txtname.Text = rdr.GetString(2);


当您告诉它从结果集中获取第三列并获得第一列使用时,该操作将失败;


will fail as you are telling it to get the third column from the result set, to get the first column use;

this.txtname.Text = rdr.GetString(0);


LukmanulHakeem.T写道:
LukmanulHakeem.T wrote:

this.txtname.Text = rdr.GetString(2 )

this.txtname.Text = rdr.GetString(2)



更改为:



Change to:

this.txtname.Text = rdr.GetString(0)



为什么只有一列(其索引为0)时使用2作为索引?



Why did you use 2 as index while you have just one column (whose index is 0)?


这篇关于索引不在Array的范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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