代码之家  ›  专栏  ›  技术社区  ›  user366312

使GridView列不可见的ASP.NET

  •  1
  • user366312  · 技术社区  · 15 年前

    这是主细节表单。主控形状是网格视图。而且,细节是一个细节视图。

    整个事情都是通过程序实现的。

    从代码中可以看到,detailsView使用主对象的ID来检索细节项。

    我需要使主网格视图的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

    1 回复  |  直到 15 年前
        1
  •  7
  •   Phaedrus    15 年前

    你考虑过使用 DataKeyNames GridView的属性?这样就可以从 GridView bu仍然访问页面加载中的“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;
        }
    }
    
    推荐文章