2017-06-18 41 views
0

您好我有一個GridView,其中,如下圖所示的代碼,我動態添加文本框:如何獲得GridView控件的行索引時,該行的文本框獲得焦點

protected void getDateControls() 
{ 
    foreach (GridViewRow grow in gdView.Rows) 
    { 
     for (int i = 7; i <= gdView.HeaderRow.Cells.Count - 1; i++) 
     { 
      string txtName = gdView.HeaderRow.Cells[i].Text; 
      System.Web.UI.WebControls.TextBox txt = new System.Web.UI.WebControls.TextBox(); 
      txt.ID = txtName; 
      txt.Width = 25; 
      txt.Font.Size = 9; 
      txt.Style.Add("text-align", "Center"); 
      txt.BackColor = Color.Black; 
      txt.ForeColor = Color.White; 
      txt.BorderStyle = System.Web.UI.WebControls.BorderStyle.None; 
      txt.AutoPostBack = true; 
      txt.TextChanged += new System.EventHandler(this.txtName_Changed); 
      grow.Cells[i].Controls.Add(txt); 
     } 
    } 
} 

現在我已經得到了行索引時,這些文本框中的任何一個獲得焦點。任何人都可以幫我完成下面的代碼。我想在設計時添加到頁面的文本框(TextBox1)中獲取行索引。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $(document).on("focus", "input[id*='txtName']", function() { 
      ////help required to get the row index.... 
     }); 
    }); 
</script> 

我不確定這是否是正確的方法。

感謝大家的期待。

回答

0

您可以通過向TextBox添加一個屬性並在javascript函數中獲取它來完成此操作。因此,首先更改foreach以添加行號。

int rowNumber = 0; 

foreach (GridViewRow grow in GridView1.Rows) 
{ 
    for (int i = 7; i <= GridView1.HeaderRow.Cells.Count - 1; i++) 
    { 
     //rest of code 

     txt.Attributes.Add("rowNumber", rowNumber.ToString());  
    } 

    rowNumber++; 
} 

然後javascript函數。您可能需要根據您的確切規格進行調整。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#<%= GridView1.ClientID %> input[type="text"]').focus(function() { 
      var rowNumber = $(this).attr("rowNumber"); 
      alert(rowNumber); 
     }); 
    }); 
</script>