자료/ASP.NET

GridView에서 안보이는 컬럼값 가져오기

네오블루 2008. 5. 14. 23:37
안녕하세요?ASP.NET 1.X를 할 때 유용하게 써먹던 팁 중 하나로DataGrid에 안보이는 컬럼을 두고 그 값을 써먹는 테크닉이 있었습니다.이 방법을 사용하게 되면 DB에서 다시 데이터를 읽어오지 않아도 되었기에코드 작성 및 성능향상에 도움이 되었었지요..그런데 2.0으로 넘어와서 GridView를 사용하게 되면이 테크닉이 먹지 않습니다.예를 들면 <asp:BoundField HeaderText="아이디" DataField="id" Visible="false" />과 같이 GridView의 특정 컬럼을 보이지 않게 하고RowCommand 이벤트 등에서 Label1.Text = GridView1.Rows[0].Cells[0].Text;과 같이 값을 읽으려고 하면 값을 읽어오지 못한다는 말입니다.이에 대한 해결방법 중 하나로  GridView의 DataKeyNames를 사용하는 방법이 있습니다.그렇지만 원래 DataKeyNames는 PrimaryKey를 저장하는 곳입니다.만일 DataKeyNames에 PrimaryKey가 아닌 값을 저장하고GridView를 통한 Update나 Delete를 하게 된다면 문제가 발생하게 됩니다.활용에 제한이 있을 수밖에 없다는 말입니다.그러면 예전에 DataGrid에서 쓰던 테크닉을 사용할 수 없느냐 하면 그렇진 않습니다.다만 약간의 코딩이 필요합니다.아래와 같이 GridView의 RowCreated 이벤트 내에서해당 컬럼의 Visible 속성을 false로 주면 됩니다.그러면 소스코드 나갑니다.[Default.aspx]<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">    <div>        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">            <Columns>                <asp:BoundField HeaderText="아이디" DataField="id"/>                <asp:BoundField HeaderText="이름" DataField="name" />                <asp:ButtonField CommandName="ShowName" Text="이름보기" />            </Columns>        </asp:GridView>        <br />        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>    </div>    </form></body></html>[Default.aspx.cs]using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            DataTable table = new DataTable();            table.Columns.Add("id", typeof(string));            table.Columns.Add("name", typeof(string));            table.Rows.Add("hskim618", "김홍석");            table.Rows.Add("taeyo", "김태영");                        GridView1.DataSource = table;            GridView1.DataBind();        }    }    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)    {        if (e.Row.Cells.Count > 1) // 바인딩된 데이터가 없는 경우 에러를 막아준다.            e.Row.Cells[1].Visible = false;    }    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)    {        if (e.CommandName == "ShowName")        {            int index = Convert.ToInt32(e.CommandArgument);            Label1.Text = GridView1.Rows[index].Cells[1].Text;        }    }}GridView 중 하나의 컬럼을 보이지 않게 하고GridView 내의 버튼을 눌렀을 경우 보이지 않는 컬럼의 값을Label1에 찍어주는 간단한 예제입니다.코드가 간단해서 특별한 설명은 필요없을 것 같군요..ASP.NET Q&A 게시판에 질문이 올라온 것을 보고간단히 예제를 만들어 보았습니다.