尝试从数据库中获取多个数据时C#出错

时间:2013-05-14 15:11:44

标签: c# sql database fetch

我在C#中有这段代码:

 private void sqlConnLabel() 
 {
        NoIDPenghuni = new SqlParameter();
        SqlConnection con = new SqlConnection(strCon);

        com2 = new SqlCommand();
        com2.Connection = con;
        con.Open();

        com2.CommandType = CommandType.StoredProcedure;
        com2.CommandText = "label";

        NoIDPenghuni.SqlDbType = SqlDbType.VarChar;
        NoIDPenghuni.Size = 50;
        NoIDPenghuni.ParameterName = "@NoIDPenghuni";
        NoIDPenghuni.Value = NoIDPenghuniC;
        NoIDPenghuni.Direction = ParameterDirection.Input;

        com2.Parameters.Add(NoIDPenghuni);

        string NamaPenghuni;
        string JKPenghuni;
        string NoTelpPenghuni;
        string AlamatPenghuni;
        string NoKamar;

        NamaPenghuni = Convert.ToString(com2.ExecuteScalar());
        JKPenghuni = Convert.ToString(com2.ExecuteScalar());
        NoTelpPenghuni = Convert.ToString(com2.ExecuteScalar());
        AlamatPenghuni = Convert.ToString(com2.ExecuteScalar());
        NoKamar = Convert.ToString(com2.ExecuteScalar());

        SqlDataReader reader = com2.ExecuteReader();
        while (reader.Read())
        {
            NamaPenghuni = reader["NamaPenghuni"] == DBNull.Value ? null : (string)reader["NamaPenghuni"];
            JKPenghuni = reader["JKPenghuni"] == DBNull.Value ? null : (string)reader["JKPenghuni"];
            NoTelpPenghuni = reader["NoTelpPenghuni"] == DBNull.Value ? null : (string)reader["NoTelpPenghuni"];
            AlamatPenghuni = reader["AlamatPenghuni"] == DBNull.Value ? null : (string)reader["AlamatPenghuni"];
            NoKamar = reader["NoKamar"] == DBNull.Value ? null : (string)reader["NoKamar"];
        }

        label9.Text = NoIDPenghuniC;
        label8.Text = NamaPenghuni;

        if (JKPenghuni == "P")
            label7.Text = "Male";
        else
            label7.Text = "Female";

        label6.Text = NoTelpPenghuni;
        label18.Text = AlamatPenghuni;

        label5.Text = NoKamar;
        con.Close();
    }

当我试图跑它时一直告诉我

  

IndexOutOfRangeException未处理。

我认为数据不会被提取到我的C#中。它只需要'NamaPenghuni'

例如:如果我使用 NoIDPenghuni ='110801101 获取数据,则NamaPenghuni应为 Priska Hapsari ,JKPenghuni应为 W ,NoTelpPenghuni应该是 08567711332 ,而AlamatPenghuni应该是 Jl 。 Mega Cinere No. 29, Cinere

但在我的本地部分,我可以看到所有这些字符串变量值都是Priska Hapsari。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

在ExecuteReader之前调用ExecuteScalar的5倍 ExecuteScalar返回第一行的第一列(只有一个结果) 调用它5次会导致所有5个变量的值相同

IndexOutOfRange异常可能是由以下要求在返回值中找到5列的ExecuteReader引起的,但我们无法看到StoredProcedure是否每行有效返回5个值