Click here to Skip to main content
15,991,108 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, im making a website which allows a user to select a film from a list of genres and then save that film choice to a database. I've also added a grid view control which allows the user to view the most selected films. Now i've got that grid view control to work as it does display the most selected films, however the column name for the column with the number of times a film has been selected has the default name of Column 1. I added a bit of code to change the name of this to "Number" but it isnt allowing me to do this? It displays an error saying "System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"


Heres my code I've used, i've marked the place in the code where the error is located.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void ButtonDatabase_Click(object sender, EventArgs e)
    {
        // set up data connection
        SqlConnection cs = new SqlConnection("Data Source=MASTER\\MASTER;Initial Catalog=FilmDB;Integrated Security=True");
        //set up adapter manager 
        SqlDataAdapter da = new SqlDataAdapter();
       
        DataSet ds = new DataSet();
        da.SelectCommand = new SqlCommand("Select FilmName, COUNT(*) FROM Film Group BY FilmName Having COUNT(*) > 1", cs);
        
        
        da.Fill(ds, "Film");
        gvFilms.DataSource = ds;
        gvFilms.DataBind();
 //This is where the error is       gvFilms.Columns[0].HeaderText = "Number";
        btnDatabase.Enabled = false;

        
    }
   }
Posted

1 solution

Is the query return anything? There shoudl always be a column 0 if there is anything returned.

But, aside from that, you don't need to change the column name there...you can do it in the query:

Select FilmName, COUNT(*) as [Number] FROM Film Group BY FilmName Having COUNT(*) > 1
 
Share this answer
 
Comments
programmer1234 17-Mar-11 16:08pm    
That worked, Thanks.

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