简体   繁体   English

当该行中的文本框获得焦点时,如何获取gridview的行索引

[英]How to get the row index of gridview when a textbox in that row gets focus

Hi I have a gridview wherein I have added textbox dynamically as shown in the code below: 嗨,我有一个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);
        }
    }
}

Now I have to get the row index when any of these textbox gets focus. 现在,当这些文本框中的任何一个获得焦点时,我都必须获取行索引。 Can anyone help me complete the following code. 谁能帮助我完成以下代码。 I want to take the row index in a textbox(TextBox1) which is added to the page during design time. 我想在设计时添加到页面的textbox(TextBox1)中获取行索引。

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

I am not sure whether this is the right approach. 我不确定这是否是正确的方法。

Thanking you all in anticipation. 谢谢大家的期待。

You can do this by adding an attribute to the TextBox and getting it in the javascript function. 您可以通过在TextBox中添加属性,然后在javascript函数中获取属性来实现。 So first change the foreach in order to add the row number. 因此,首先更改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++;
}

And then the javascript function. 然后是javascript函数。 You may need to adjust it to your exact specifications. 您可能需要将其调整为确切的规格。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM