Bryan
Bryan

Reputation: 8697

Unable to change header title via headertext

I'm trying to edit my gridview header title however, unfortunately it doesn't work

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source = localhost; Initial Catalog = project; Integrated Security= SSPI";
conn.Open();

DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter("SELECT policeid, password, email, nric, fullname, contact, address, location From LoginRegisterPolice where pending='pending'", conn);
da.Fill(ds);

GVVerify.DataSource = ds;
GVVerify.DataBind();
GVVerify.Columns[1].HeaderText = "Police ID ";
GVVerify.Columns[2].HeaderText = "Password";
GVVerify.Columns[3].HeaderText = "Email ";
GVVerify.Columns[4].HeaderText = "NRIC ";
GVVerify.Columns[5].HeaderText = "Full Name ";
GVVerify.Columns[6].HeaderText = "Contact ";
GVVerify.Columns[7].HeaderText = "Address ";
GVVerify.Columns[8].HeaderText = "Location ";

conn.Close();

This is the error i received

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

I have checked that my column index is not negative and it's the correct column number as well. I have added allowgenerateselectbutton in my gridview. Therefore, i started it with 1-8 instead of 0.

Upvotes: 0

Views: 65

Answers (3)

Damith
Damith

Reputation: 63105

You can do it by simply using column alias in your select SQL, no need to do it from code.

SELECT policeid as [Police ID] , password as [Password] ...............

Upvotes: 3

Rahul
Rahul

Reputation: 5636

You have to try from Index 0 or try different approach like

GVVerify.Columns[0].HeaderText  = "Police ID ";
------------------------------------
--------------------------------------

or

GVVerify.Columns["columnname"].HeaderText  = "Police ID ";
------------------
-------------------

Upvotes: 0

David Colwell
David Colwell

Reputation: 2590

The columns property is a zero based array. Unless there is a hidden first column you are starting at 1. Re-number the indices to 0-7 instead of 1-8.

http://msdn.microsoft.com/en-US/library/system.windows.forms.datagridview.columns(v=vs.80).aspx

    GVVerify.Columns[0].HeaderText = "Police ID ";
    GVVerify.Columns[1].HeaderText = "Password";
    GVVerify.Columns[2].HeaderText = "Email ";
    GVVerify.Columns[3].HeaderText = "NRIC ";
    GVVerify.Columns[4].HeaderText = "Full Name ";
    GVVerify.Columns[5].HeaderText = "Contact ";
    GVVerify.Columns[6].HeaderText = "Address ";
    GVVerify.Columns[7].HeaderText = "Location ";

Upvotes: 1

Related Questions