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();
            // Write this line after above two
            GridViewCategory.Columns[0].HeaderText = "Header text";
        }
    }
}
于 2013-04-03T18:08:56.433 に答える
0

データを Columns[0] に割り当てるコードの時点では、まだ 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 に答える
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 に答える