Search code examples
c#sqlexecutereader

ExecuteReader, Adding Values to List, index out of range


Hello I have following code:

  SqlCeCommand commandArbeitstage= new SqlCeCommand("select count(IDStundensatz) as Gesamt from tblstunden Where IDPersonal = @IDPersonal Group by datepart(month, Datum) Order By datepart(month, Datum)", verbindung);

            commandArbeitstage.Parameters.Add("IDPersonal", SqlDbType.Int);
            commandArbeitstage.Parameters["@IDPersonal"].Value = IDPersonal;


            SqlCeDataReader readerArbeitstage = commandArbeitstage.ExecuteReader();
            List<Int32> Arbeitstage = new List<Int32>();

                while (readerArbeitstage.Read())
                {
                    Arbeitstage.Add(readerArbeitstage.GetInt32(0));
                }
                Arbeitstage.GetRange
                textBox53.Text = Arbeitstage[0].ToString();
                textBox60.Text = Arbeitstage[1].ToString();
                textBox68.Text = Arbeitstage[2].ToString();

The query is counting working days in a table and order them by datepart. So I have one column [Gesamt] and 12 rows. I would like to assign the number of worked days to 12 textboxes. I have done that above for January to March.

If I add another line of code for april,

     textBox74.Text = Arbeitstage[3].ToString();

I get an out of range exception. I think the problem occurs because there is no record for April and hence the index[4] in List Arbeitstage doesn't exist. So therefor I would like to assign the textBox74.Text a zero.

Anybody an idea?

Many thanks in advance!


Solution

  • If you need the number of days for each month, you can use an array that is inialised with zeroes to store the numbers for each month. You can then reference the values for each month (by index 0 to 11). You will also need to change the query to return the month number.

    SqlCeCommand commandArbeitstage= new SqlCeCommand("select datepart(month, Datum) as Month, count(IDStundensatz) as Gesamt from tblstunden Where IDPersonal = @IDPersonal Group by datepart(month, Datum) Order By datepart(month, Datum)", verbindung);
    
    commandArbeitstage.Parameters.Add("IDPersonal", SqlDbType.Int);
    commandArbeitstage.Parameters["@IDPersonal"].Value = IDPersonal;
    
    
    SqlCeDataReader readerArbeitstage = commandArbeitstage.ExecuteReader();
    Int32[] Arbeitstage = new Int32[12];
    
    while (readerArbeitstage.Read())
    {
        Arbeitstage[readerArbeitstage.GetInt32(0) - 1]  = readerArbeitstage.GetInt32(1));
    }
    textBox53.Text = Arbeitstage[0].ToString();  // January
    // ... and so on up to 11