2011-05-16 2 views
0

내 프로젝트에서 데이터베이스와 연결되지 않은 격자보기가 있습니다. 그것은 소스로 데이터 테이블을 가지고 행은 "AddNewRowBtn"의 버튼 클릭 이벤트에 동적으로 추가됩니다. 각 행에는 '제거'버튼이 있습니다. 행에서 제거 버튼을 클릭하면 해당 행을 삭제해야합니다. 그 때문에 버튼이 클릭 된 행의 행 인덱스가 필요합니다. 행의 행 인덱스를 얻는 방법?격자보기에서 행 색인 얻기

내 .aspx.cs 페이지의 코드는 다음과 같습니다.

using System; 
using System.Collections; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 

public partial class AppForm : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    if (!IsPostBack) 
    { 
     setInitialRow(); 
    } 
} 
protected void addRowBtn_Click(object sender, EventArgs e) 
{ 
    AddNewRow(); 
} 
public void setInitialRow() 
{ 
    DataTable Table = new DataTable(); 
    DataRow dr = null; 
    Table.Columns.Add(new DataColumn("Qualification", typeof(string))); 
    Table.Columns.Add(new DataColumn("QualiId", typeof(Int32))); 
    Table.Columns.Add(new DataColumn("Percentage", typeof(float))); 
    Table.Columns.Add(new DataColumn("PassingYear", typeof(Int32))); 
    Table.Columns.Add(new DataColumn("InstituteName", typeof(string))); 
    dr = Table.NewRow(); 

    dr["Percentage"] = DBNull.Value; 
    dr["PassingYear"] = DBNull.Value; 
    dr["InstituteName"] = string.Empty; 

    Table.Rows.Add(dr); 
    Session.Add("CurTable", Table); 
    QualificationGrid.DataSource = Table; 
    QualificationGrid.DataBind(); 


    //ArrayList Array = new ArrayList(); 
    //DataSet ds = new DataSet(); 
    DropDownList DDL = (DropDownList)QualificationGrid.Rows[0].Cells[0].FindControl("QualificationList"); 
    FillDropDownList(DDL); 
} 
public void AddNewRow() 
{ 
    if (Session["CurTable"] != null) 
    { 
     DataTable CurTable = (DataTable)Session["CurTable"]; 
     DataRow CurRow = null; 
     if (CurTable.Rows.Count > 0) 
     { 
      CurRow = CurTable.NewRow(); 
      CurTable.Rows.Add(CurRow); 
      Session.Add("CurTable", CurTable); 
      for (int count = 0; count < CurTable.Rows.Count - 1; count++) 
      { 
       DropDownList DDL = (DropDownList)QualificationGrid.Rows[count].Cells[0].FindControl("QualificationList"); 
       TextBox PercentageBox = (TextBox)QualificationGrid.Rows[count].Cells[1].FindControl("percentageBox"); 
       DropDownList YearList = (DropDownList)QualificationGrid.Rows[count].Cells[0].FindControl("yearList"); 
       TextBox InstituteNameBox = (TextBox)QualificationGrid.Rows[count].Cells[1].FindControl("InstituteNameBox"); 

       CurTable.Rows[count]["Percentage"] = PercentageBox.Text; 
       CurTable.Rows[count]["PassingYear"] = YearList.SelectedItem.Text; 
       CurTable.Rows[count]["InstituteName"] = InstituteNameBox.Text; 
       CurTable.Rows[count]["Qualification"] = DDL.SelectedItem.Text; 
       CurTable.Rows[count]["QualiId"] = DDL.SelectedValue; 
      } 
      QualificationGrid.DataSource = CurTable; 
      QualificationGrid.DataBind(); 
     } 
    } 
    setPreviousData(); 
} 
public void setPreviousData() 
{ 
    int RowIndex = 0; 
    if (Session["CurTable"] != null) 
    { 
     DataTable RestoreTable = (DataTable)Session["CurTable"]; 
     if (RestoreTable.Rows.Count > 0) 
     { 
      for (int row = 0; row < RestoreTable.Rows.Count; row++) 
      { 
       DropDownList DPList = (DropDownList)QualificationGrid.Rows[row].Cells[0].FindControl("QualificationList"); 
       TextBox PercentageBox = (TextBox)QualificationGrid.Rows[row].Cells[1].FindControl("percentageBox"); 
       // TextBox YearBox = (TextBox)QualificationGrid.Rows[row].Cells[2].FindControl("yearBox"); 
       DropDownList YearList = (DropDownList)QualificationGrid.Rows[row].Cells[0].FindControl("yearList"); 
       TextBox InstituteName = (TextBox)QualificationGrid.Rows[row].Cells[3].FindControl("InstituteNamebox"); 

       FillDropDownList(DPList); 

       if (row < RestoreTable.Rows.Count - 1) 
       { 
        PercentageBox.Text = RestoreTable.Rows[row]["Percentage"].ToString(); 
        InstituteName.Text = RestoreTable.Rows[row]["InstituteName"].ToString(); 

        DPList.ClearSelection(); 
        DPList.Items.FindByText(RestoreTable.Rows[row]["Qualification"].ToString()).Selected = true; 

        YearList.ClearSelection(); 
        YearList.Items.FindByText(RestoreTable.Rows[row]["PassingYear"].ToString()).Selected = true; 
       } 
       RowIndex++; 
      } 
     } 
    } 
} 
private ArrayList FillArrayList() 
{ 
    ArrayList ArrayList = new ArrayList(); 
    DataSet ds = new DataSet(); 
    using (DataOperation oDo = new DataOperation()) 
    { 
     DataTable dt = oDo.DropDownList("select * from tblQualificationMaster"); 
     for (int count = 0; count < dt.Rows.Count; count++) 
     { 
      ArrayList.Add(new ListItem(dt.Rows[count][1].ToString(), dt.Rows[count][0].ToString())); 
      //ArrayList.Add(new ListItem(ds.Tables[0].Rows[count][1].ToString(), ds.Tables[0].Rows[count][0].ToString())); 
     } 
    } 
    return ArrayList; 
} 
private void FillDropDownList(DropDownList DDL) 
{ 
    ArrayList ArrayList = FillArrayList(); 
    foreach (ListItem item in ArrayList) 
    { 
     DDL.Items.Add(item); 
    } 
    DDL.Items.Insert(0, "Select Year"); 
} 

protected void removeBtn_Click(object sender, EventArgs e) 
{ 
    int row = QualificationGrid.c 
} 

}

답변

2

을 (SelectedRow를 사용하여, 확실히 간단한 방법입니다 당신을 위해 작동하는 경우), 당신은 또한 얻을 갈 수 있습니다 실제 행 자체의 RowIndex입니다. 다음 (예를 들어, 보낸 사람의 유형 ImageButton)를 사용합니다 (sender 당신이 Button, LinkButton, 또는 ImageButton은) 버튼을 클릭에 대한 이벤트 핸들러에서

는 :

(GridViewRow)(((ImageButton)sender).Parent.Parent) 

GridViewRow로 행을 얻으려면 를 입력 한 다음 GridViewRow.RowIndex 속성을 사용하십시오.

편집 : @ Alison의 링크에서 세 번째 옵션이이 방법과 비교하여 어떻게 작동하는지 모르겠습니다.이 경우 sender.Parent.Parent을 사용하여 실제 테이블 행을 얻습니다. 반면 NamingContainer을 사용합니다. 당신의 GridView가 전혀 변경되지 않았다면 (행이 테이블 자체에서 추가/삭제됨) NamingContainer을 사용하여 문제가 발생할 수 있다고 말하고 싶습니다. 아래 켰을 때,

1

당신은 당신의 삭제 버튼에 명령 인수 속성을 추가 할 수 있습니다

<asp:TemplateField> 
     <ItemTemplate> 
        <asp:Button ID="btnDelete" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' CommandName="Delete" /> 
     </ItemTemplate> </asp:TemplateField> 

다음 당신은 아래와 같이 이벤트 만들어야합니다 :

protected void DeleteRowBtn_Click(object sender,GridViewCommandEventArgs e) 
{ 
    int rowIndex = Convert.ToInt32(e.CommandArgument); 
} 

을하고있는 gridview 마크 업에서 당신 이벤트를 바인드해야합니다.

<asp:GridView ID="GridView1" runat="server" AutoGenerateEditButton="True" 
    DataKeyNames="Id" 
    onrowcommand="DeleteRowBtn_Click" > 
+0

위의 예와 같이 GridView DataKeys/DataKeyName 속성을 사용하십시오. 이것을 의도 된대로하십시오. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeys.aspx – mikey