ASP.NET AJAX
[ GridView ] DataKeys , RowDataBound (데이터바인딩)간단한 사용법
스티커
2009. 5. 20. 14:46
선택한 행의 데이터 키 값을 확인하는 방법 과 EditItemTemplate 에서 컨트롤의 값을 가져오기
(사용자작업일때)
다음 코드 예제에서는 DataKeys 속성을 사용하여 GridView 컨트롤에서 선택한 행의 데이터 키 값을 확인하는 방법을 보여 줍니다.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { // 수정할려는 수정템플릿의 값을 가져오는 방법 GridViewRow row = GridView1.Rows[e.RowIndex]; TextBox CTextBoxbMove_url = (TextBox)row.FindControl("TextBoxbMove_url"); //GridView의 고유값을 가져오는 방법 //GridView 에서 DataKeyNames가 설정되어져있어야함 int index = GridView1.SelectedIndex; Response.Write("e.Keys::: " + this.GridView1.DataKeys[e.RowIndex].Value ); //데이터베이스에 저장하기 SqlConnection conn = new SqlConnection(AspxUtil.GetDBStr()); conn.Open(); SqlCommand comm = new SqlCommand("UPDATE SEARCH_BAR_TEXT_BANNER SET banner_text =@banner_text ,move_url=@move_url WHERE IDX=@idx ", conn); comm.Parameters.Add("@banner_text", SqlDbType.VarChar).Value = ((TextBox)row.FindControl("TextBoxbMove_url")).Text; comm.Parameters.Add("@move_url", SqlDbType.VarChar).Value = ((TextBox)row.FindControl("TextBoxbMove_url")).Text; comm.Parameters.Add("@idx", SqlDbType.Int).Value = this.GridView1.DataKeys[e.RowIndex].Value; comm.ExecuteNonQuery(); GridView1.DataBind(); this.GridView1.EditIndex = -1; }
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="idx"
OnRowUpdating="GridView1_RowUpdating"
>
<asp:TemplateField HeaderText="banner_open" >
<EditItemTemplate>
<asp:TextBox ID="TextBoxBanner_open" runat="server" Text='<%# Bind("banner_open") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
리스트 뿌려줄때 그안에 속한 컨트롤 제어하기 DataBound
데이터가 바운드될때 dropDownList를 찾아서 데이터베이스에 저장된 값에 따라 셀렉트를 선택한다
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //데이터값 가져오기 DataRowView dr = (DataRowView)e.Row.DataItem; //DropDownListBanner_open 이름의 컨트롤 찾기 DropDownList dl = (DropDownList)e.Row.FindControl("DropDownListBanner_open"); //만약컨트롤이 있다면 selected 시키자 if (dl != null){ dl.SelectedIndex = (int)dr["banner_open"]; } } }
RowCommand 에서 데이터 접근하기
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { //컨트롤텍스트에 접근하기 string m_id = this.GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[1].Text; //DataKeys 에 접근하기 //Response.Write(this.GridView1.DataKeys[ int.Parse( e.CommandArgument.ToString() ) ].Value); }
<ItemTemplate>일때 접근방법
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { ImageButton btn = ((ImageButton)e.CommandSource); int row_num = (int)((GridViewRow)btn.Parent.Parent).RowIndex; }