隐藏GridView列 [英] Hide gridview column

查看:87
本文介绍了隐藏GridView列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Can some one tell me why this code is giving me these error:

<pre lang="msil">Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 34:         else
Line 35:         {
Line 36:             grdAvailableStuff.HeaderRow.Cells[2].Visible = false;
Line 37:
Line 38:</pre>


Code below

<pre lang="cs">protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            radDoctors.Checked = false;
            radNurses.Checked = false;
        }
        if (grdAvailableStuff.Columns.Count == 0)
        {
            grdAvailableStuff.Columns[2].Visible = false;


        }
        else
        {
            grdAvailableStuff.HeaderRow.Cells[2].Visible = false;


            foreach (GridViewRow grd in grdAvailableStuff.Rows)
            {
                grd.Cells[2].Visible = false;


            }
        }

    }</pre>

推荐答案

RowCreated方法中执行此操作.您可以使用类似于以下内容的代码:

Do this in the RowCreated method. You can use code similar to the following:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        e.Row.Cells[0].Visible =
            e.Row.Cells[1].Visible =
            e.Row.Cells[3].Visible = false;

        // and so on and so forth...
    }
}



您可以在RowDataBound事件中操作数据和单元格.



You can manipulate data and cells in the RowDataBound event.


您也可以在.aspx页中使用
执行此操作
如果条件
将全局变量设置为.cs文件

使用if条件检查该全局变量的值
并且您可以相应地看到或隐藏该列.
you can also do this in .aspx page using

if condition
set the global variable to the .cs file

check the value of that global variable using if condition
and you can visible or invisible that column accordingly.


我建​​议通过ColumnName而不通过Index

I suggest that go via ColumnName not via Index

if (GridView1.Columns["FieldID"] != null) GridView1.Columns["FieldID"].Visible = false;



而且,对于设置列的可见性属性,无需使用RowDataBound事件.绑定网格后,立即调用上面的行



And for setting visibility property for the columns, no need to use RowDataBound event. Directly after binding the grid call the above line


这篇关于隐藏GridView列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆