指数超出范围。必须是非负数且小于集合的大小

时间:2013-04-10 12:00:41

标签: c# asp.net

任何人都可以建议在asp.net c#

中将列表框中的多个选定值存储到数据库的代码
 string day = dataGridView1.Rows[0].Cells[0].Value.ToString();
 //DateTime.Now.DayOfWeek.ToString();
 dataGridView1.Rows[0].Cells[1].Value = 
                Convert.ToDateTime(day.ToString())).DayOfWeek.ToString();
 for (int i = 1; i < 10; i++)
 {
     DateTime dtd = Convert.ToDateTime(day).Date;
     dtd = dtd.AddDays(7);
     dataGridView1.Rows[i].Cells[0].Value = dtd;
     DateTime date = dtd;
    dataGridView1.Rows[i ].Cells[1].Value = 
                   (Convert.ToDateTime(date.ToString())).DayOfWeek.ToString();
  }
}

错误

Index was out of range. Must be non-negative and less than the size of the collection. 
Parameter name: index.

3 个答案:

答案 0 :(得分:5)

请注意,对于X的大小,index为0到(x-1)。

所以也许你想用:

for (int i = 0; i < 9; i++)

或者使用i<dataGridView1.Rows.Count()作为循环停止条件语句而不是i <9。

答案 1 :(得分:0)

在开始访问行或单元格之前,您应该创建一个! 我希望这段代码可以帮到你

dataGridView1.Columns.Add("date", "Date");
        dataGridView1.Columns.Add("day", "Day");

        var day = DateTime.Now;
        DataGridViewRow row = new DataGridViewRow();
        DataGridViewCell cell = new DataGridViewTextBoxCell();
        cell.Value = (Convert.ToDateTime(day.ToString())).DayOfWeek.ToString();
        row.Cells.Add(cell);
        dataGridView1.Rows.Add(row);
        for (int i = 1; i < 10; i++)
        {
            DateTime dtd = Convert.ToDateTime(day).Date;
            dtd = dtd.AddDays(7);
            row = new DataGridViewRow();
            cell = new DataGridViewTextBoxCell();
            cell.Value = dtd.ToString();
            row.Cells.Add(cell);
            DateTime date = dtd;
            cell = new DataGridViewTextBoxCell();
            cell.Value = (Convert.ToDateTime(date.ToString())).DayOfWeek.ToString();
            row.Cells.Add(cell);
            dataGridView1.Rows.Add(row);
        }

答案 2 :(得分:-1)

确保dataGridView可见属性为“visible = true”