当前位置:  开发笔记 > 后端 > 正文

asp.net使gridView列不可见

如何解决《asp.net使gridView列不可见》经验,为你挑选了1个好方法。

这是Master-Detail表单.Master是一个GridView.而且,细节是一个DetailsView.

整个过程以编程方式实现.

从代码中可以看出,DetailsView使用Master-objects的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 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();
        }
    }

替代文字



1> Phaedrus..:

您是否考虑过使用DataKeyNamesgridview 的属性?这样您就可以从GridViewbu中删除'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;
    }
}


使用AutoGenerateColumns ="true"时,不会填充GridView的列集合,这就是您接收索引超出范围异常的原因.
推荐阅读
重庆制造漫画社
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有