0

我正在尝试编辑我的 gridview 标题,但不幸的是它不起作用

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();

这是我收到的错误

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

我检查了我的列索引不是负数,它也是正确的列号。我已经allowgenerateselectbutton在我的网格视图中添加了。因此,我从 1-8 而不是 0 开始。

4

3 回答 3

3

您只需在您的选择 SQL 中使用列别名即可完成此操作,无需从代码中执行此操作。

SELECT policeid as [Police ID] , password as [Password] ...............
于 2013-07-19T04:11:35.707 回答
1

columns 属性是一个从零开始的数组。除非有隐藏的第一列,否则您从 1 开始。将索引重新编号为 0-7 而不是 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 ";
于 2013-07-19T03:56:37.307 回答
0

您必须尝试Index 0或尝试不同的方法,例如

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

or

GVVerify.Columns["columnname"].HeaderText  = "Police ID ";
------------------
-------------------
于 2013-07-19T03:59:05.383 回答