Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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)


}
Posted

LukmanulHakeem.T wrote:
where CCode



You've used CCode. Do you need to use Code instead?
 
Share this answer
 
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);
 
Share this answer
 
LukmanulHakeem.T wrote:
this.txtname.Text = rdr.GetString(2)


Change to:
this.txtname.Text = rdr.GetString(0)


Why did you use 2 as index while you have just one column (whose index is 0)?
 
Share this answer
 
v2
Well you are accessing wrong column, as you are having only one column in you select statement. Just change your line

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


with

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

Then it should work.
 
Share this answer
 
USE THE DEBUGGER.

It would have allowed you to discover that there is only one item in the rdr object. Using a value greater than 0 will almost always result in an exception.
 
Share this answer
 
v3
I have answer to your problem.
Your query does not return any row.. this means your reader has now rows. so how you can write

(if dr.read())   <br />
{<br />
..<br />
..<br />
}


use this

<br />
SqlCommand cmd = new SqlCommand();<br />
SqlDataReader rdr = null;<br />
conn.Open();<br />
String str = "select name from Company where CCode='12345'";<br />
cmd.CommandText = str;<br />
cmd.Connection = conn;<br />
rdr = cmd.ExecuteReader();<br />
if (rdr.HasRows)<br />
{<br />
while (rdr.read())<br />
{System.Windows.MessageBox.Show("Test");<br />
<br />
this.txtname.Text = rdr["column name"];<br />
}<br />
<br />
}<br />

I think this will definitely help you

if yes plz reply me..
inder2305@gmail.com
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900