当数据库中的日期检索时,索引超出了数组的范围

时间:2013-03-15 13:20:22

标签: sql-server-2005 ado.net

dateTimePicker2.Value = Convert.ToDateTime((sdr[1]),   
                        CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);

我从SqlDataReader中提取日期值,但是读取它会导致错误:

  

索引超出了数组的范围

cmd = new SqlCommand("Physio_cure_Search", con);
cmd.CommandType = CommandType.StoredProcedure;   
cmd.Parameters.Add("@RegisterNo", SqlDbType.VarChar).Value = txtsearch.Text;    
SqlDataReader sdr = cmd.ExecuteReader();    
while (sdr.Read())
{
    txtregistrationno.Text = sdr.GetString(0);
    //giving error on this line:    
    dateTimePicker2.Value = Convert.ToDateTime((sdr[1]), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);        
}

此处sdrSqlDataReader的实例,sdr [1]用于检索数据库值。 如何解决这个问题?

ALTER procedure [dbo].[Physio_cure_Search]
@RegisterNo varchar(500)   
As
begin
    select Convert(varchar(100),DateOfBirth,103) as DateOfBirth 
    from Physio_cureTable

    select RegisterNo,RegistrationDate,Stimulation,PationName,DateOfBirth,ContactNo,Occupation,Age,
    Sex,Weight,Chief_Complain,Investigation_Result,PastHistoryAny,Physical_Examination,Ref_By_Doctor,Medications,Prognosis,Electro_Therapy,Neuro_Rehabilitation,Ortho_Rehabilitation,Cardio_Pulmonery_Rehabilitation,Sports_Rehabilitation 

    from Physio_cureTable where RegisterNo=@RegisterNo and Syncoperation <>'D'
end

1 个答案:

答案 0 :(得分:0)

您有两个问题:您的存储过程返回2个结果集,而您正在运行第一个结果集。其次,您的C#代码将无法正常工作。

1- 删除第一个结果集select Convert(varchar(100),DateOfBirth,103) as DateOfBirth from Physio_cureTable。这对你的C#代码没用。

2-修改您的代码以显式按列名检索值,而不是通过数字索引

 while (sdr.Read())
 {
     txtReg.Text = sdr["RegisterNo"].ToString();
     dateTimePicker2.Value = 
         Convert.ToDateTime(sdr["RegistrationDate"].ToString(),   
                            CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
 } 

3-如果此调用代码仅使用此存储过程,则从select语句中删除所有未使用的列。

select  RegisterNo, RegistrationDate
from Physio_cureTable where RegisterNo=@RegisterNo and Syncoperation <>'D'