본문 바로가기
Web Program/Asp.net Lecture

gridview 컬럼 hide 시키기

by 현이빈이 2009. 5. 21.
반응형
gridview 에서 column 을 visible = false 시킬경우
데이타 값까지 없어진다.

이런 황당한 경우가..
정말 삭제하는 기능이다.

데이타는 유지하면서 column 을 HIde 시켜보자

gridview 이벤트에 RowCreated 이벤트를 생성한다.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
 {  
  e.Row.Cells[2].Visible = false;  
 }    

와 같이 추가 하자

하지만 이렇게 할 경우 에러가 발생한다.

왜일까..

RowType 에 Footer 가 없기 떄문이다.

이렇게 고쳐보자

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
 {
  if (e.Row.RowType == DataControlRowType.Header ||
      e.Row.RowType == DataControlRowType.DataRow)
  {
   e.Row.Cells[2].Visible = false;
  }
 }

이렇게 하면 된다.

참고 자료

Create the Row Created event handler and do the following:

Public Sub myGrid_OnRowCreated(ByVal sender As Object, ByVal e As Web.UI.WebControls.GridViewRowEventArgs) Handles myGrid.RowCreated

        'Those columns you don't want to display you config here,

        'you could use a for statement if you have many :)

        e.Row.Cells(1).Visible = False

End Sub


Why this works? Because the event is called after the data is bound to the grid... This ensures that the column has been databound and then it is hidden.

Another solution can be to use the following to bind the data to the GridView.


Public Sub myTestFunction()

        'To hide a column, set its width to zero or use MappingType

        Dim strCON As String = "<Connection String>"

        Dim strQuery As String = "<QueryString>"

        Dim da As Data.SqlClient.SqlDataAdapter

        Dim ds As Data.DataSet

        Try

            Dim conn As New Data.SqlClient.SqlConnection(strCON)

            da = New Data.SqlClient.SqlDataAdapter(strQuery, CON)

            ds = New Data.DataSet

            da.Fill(ds, "tblData")

            conn.Close()

        Catch ex As Exception

            'Do error handling here...

        End Try

        'Here you can HIDE the Column

        ds.Tables("tblData").Columns(colIndex).ColumnMapping = Data.MappingType.Hidden

        myGrid.DataSource = ds.Tables("tblData")

End Sub

반응형