无法通过headertext更改标题

本文关键字:标题 headertext | 更新日期: 2023-09-27 18:23:56

我正在尝试编辑我的网格视图标题,但不幸的是,无法工作

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。

无法通过headertext更改标题

您只需在选择的SQL中使用列别名就可以做到这一点,而无需从代码中完成。

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

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 ";

您必须从Index 0开始尝试,或者尝试不同的方法,如

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