2009-11-30 20 views
1

這是一個主 - 明細表格。 Master是一個GridView。而Detail則是一個DetailsView。asp.net使gridView列隱形

整個事情是通過編程實現的。

從代碼中可以看到,DetailsView使用主對象的ID來檢索Detail項。

我需要使Master-GridView的ID列不可見。因爲這對頁面的用戶來說是無足輕重的。但它不能損害頁面邏輯。

但代碼行GridView1.Columns[1].Visible = false;正在生成異常。

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

我該如何解決這個問題?

public partial class _Default : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      if (!IsPostBack) 
      { 
       BindData(); 
      } 
     } 

     protected void BindData() 
     { 
      List<Order> orders = Order.Get(); 

      GridView1.DataSource = orders; 
      GridView1.DataBind(); 

      // This is giving Error...............!!! 
      GridView1.Columns[1].Visible = false; 

      // At first, when the page first loads, 
      //  GridView1.SelectedIndex == -1 
      // So, this is done to automatically select the 1st item. 
      if (GridView1.SelectedIndex < 0) 
      { 
       GridView1.SelectedIndex = 0; 
      } 

      int selRowIndex = GridView1.SelectedIndex; 

      int selMasterId = Convert.ToInt32(GridView1.Rows[selRowIndex].Cells[1].Text); 

      Order master = Order.Get(selMasterId); 

      labItemsCount.Text = master.Items.Count.ToString(); 

      DetailsView1.DataSource = master.Items; 
      DetailsView1.DataBind();    
     } 

     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      BindData(); 
     } 

     protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e) 
     { 
      DetailsView1.PageIndex = e.NewPageIndex; 

      BindData(); 
     } 
    } 

alt text

+0

什麼是錯誤? – Phaedrus 2009-11-30 17:49:02

回答

7

你有沒有使用的GridView的DataKeyNames性能考慮?這樣,您可以從GridView bu刪除'id'列,但仍然可以訪問Page_Load中的'id'值。

DataKeyNames = "id" 

然後你可以像這樣得到id的值。

int selRowIndex = GridView1.SelectedIndex; 
int selMasterId = Convert.ToInt32(GridView.DataKeys[selRowIndex].Value); 
Order master = Order.Get(selMasterId); 

或者,你可以嘗試改變在OnRowBound事件GridView的列的可見性。

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header || 
     e.Row.RowType == DataControlRowType.DataRow || 
     e.Row.RowType == DataControlRowType.Footer) 
    { 
     e.Row.Cells[1].Visible = false; 
    } 
} 
+0

你有AutoGenerateColumns =「true」嗎? – Phaedrus 2009-11-30 18:01:43

+0

是的,我已經設置爲true。 – anonymous 2009-11-30 18:05:42

+4

使用AutoGenerateColumns =「true」時,不會填充GridView的列集合,這就是您收到索引超出範圍異常的原因。 – Phaedrus 2009-11-30 18:11:02