Asp.net 如何将标题文本更改为网格视图

Asp.net 如何将标题文本更改为网格视图,asp.net,Asp.net,我有两个专栏 在“代码隐藏”中,我有以下内容: protected void Page_Load(object sender, EventArgs e) { string connectionString = cs.getConnection(); string query = "SELECT ID , NAME FROM PROFITCATEGORIES"; using (SqlConnection myConnection = n

我有两个专栏 在“代码隐藏”中,我有以下内容:

 protected void Page_Load(object sender, EventArgs e)
    {


        string connectionString = cs.getConnection();
        string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
        using (SqlConnection myConnection = new SqlConnection(connectionString))
        {
            myConnection.Open();
            SqlCommand command = new SqlCommand(query, myConnection);
            using (SqlDataReader rdr = command.ExecuteReader())
            {

                GridViewCategory.DataSource = rdr;
                GridViewCategory.DataBind();
GridViewCategory.Columns[0].HeaderText = "Header text"; // ERROR IS HERE

            }
        }



    }
但这给了我一个错误:

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

此行出错:GridViewCategory.Columns[0]。HeaderText=标题文本

在将gridview中的列绑定到某个数据源之前,gridview中不会有任何列。尝试一下你的代码,不做任何改动

protected void Page_Load(object sender, EventArgs e)
{
    string connectionString = cs.getConnection();
    string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
    using (SqlConnection myConnection = new SqlConnection(connectionString))
    {
        myConnection.Open();
        SqlCommand command = new SqlCommand(query, myConnection);
        using (SqlDataReader rdr = command.ExecuteReader())
        {                
            GridViewCategory.DataSource = rdr;
            GridViewCategory.DataBind();
            // Write this line after above two
            GridViewCategory.Columns[0].HeaderText = "Header text";
        }
    }
}

在代码中将数据分配给列[0]时,由于尚未绑定GridView,因此没有列。重新排列代码的顺序:

        using (SqlDataReader rdr = command.ExecuteReader())
        {
            GridViewCategory.DataSource = rdr;
            GridViewCategory.DataBind();
            If(GridViewCategory.Columns.Any())
               GridViewCategory.Columns[0].HeaderText = "Header text";
        }
请试试这个

protected void Page_Load(object sender, EventArgs e)
{
    string connectionString = cs.getConnection();
    string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
    using (SqlConnection myConnection = new SqlConnection(connectionString))
    {
        myConnection.Open();
        SqlCommand command = new SqlCommand(query, myConnection);
        using (SqlDataReader rdr = command.ExecuteReader())
        {                
            GridViewCategory.DataSource = rdr;
            GridViewCategory.DataBind();

            if (GridViewCategory.Rows.Count > 0)
            {
                 GridViewCategory.HeaderRow.Cells[0].Text = "Header text";
            }

        }
    }
}

我把它向上移动,但仍然有同样的错误我在错过其他东西之前尝试了它