问题描述
我的数据库中有一个表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)
}
推荐答案
其中CCode
您已经使用了CCode.您是否需要使用代码?
You''ve used CCode. Do you need to use Code instead?
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);
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的范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!