2013-04-03 34 views
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 =「標題文本」;

+0

我重新編輯我的帖子 – Krasimir

回答

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

我動起來了,但還是老樣子同樣的錯誤,我嘗試它,我想念別的 – Krasimir

0

在代碼中的點試試你的代碼,你將數據分配到列[0],你有沒有列,因爲你還沒有綁定的GridView的呢。重新排列您的代碼的順序:

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

仍無法正常工作之前 – Krasimir

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

     } 
    } 
}