1

我在代码后面有 2 列我有这个:

 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 = "Header text";

4

3 回答 3

0

请试试这个。

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

        }
    }
}
于 2014-04-08T05:31:11.323 回答
0

在将其绑定到某个数据源之前,您将在 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";
        }
    }
}
于 2013-04-03T18:08:56.433 回答
0

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

        using (SqlDataReader rdr = command.ExecuteReader())
        {
            GridViewCategory.DataSource = rdr;
            GridViewCategory.DataBind();
            If(GridViewCategory.Columns.Any())
               GridViewCategory.Columns[0].HeaderText = "Header text";
        }
于 2013-04-03T18:09:00.347 回答