【问题标题】:How can I access DataGridRow from a textbox on that row?如何从该行的文本框中访问 DataGridRow?
【发布时间】:2010-10-25 19:52:32
【问题描述】:

在 DataGrid 中,当文本框中的文本发生更改时,我想将该行中另一个字段的值添加到数组中。

public void txtTitle_TextChanged(object sender, EventArgs e)
{
    TextBox titleBox = (TextBox)sender;
    DataGridItem myItem = (DataGridItem)titleBox.Parent.Parent;
    string test = DataBinder.Eval(myItem.DataItem, "prod_id").ToString();
}

但是 myItem.DataItem 的计算结果为 null。我期待它评估为 DataRowView?

【问题讨论】:

    标签: c# .net datagrid datarowview


    【解决方案1】:

    如果您执行以下操作,您可以触发 TextChanged 事件:

    <asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" 
        onitemdatabound="DataGrid1_ItemDataBound">
        <Columns>
            <asp:TemplateColumn HeaderText="Test">
                <ItemTemplate>
                    <asp:TextBox OnTextChanged="txtBox_TextChanged" ID="TextBox1" runat="server" AutoPostBack="True"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateColumn>
            <asp:BoundColumn DataField="Name" HeaderText="Test 1"></asp:BoundColumn>
        </Columns>
    </asp:DataGrid>
    

    您会注意到我设置了以下属性: 自动回邮=“真” 我还手动将 OnTextChanged="txtBox_TextChanged" 添加到文本框中。

    在我后面的代码中:

    protected void txtBox_TextChanged(object sender, EventArgs e)
    {
        TextBox txtBox = (TextBox)sender;
        Label1.Text = txtBox.Text;
    }
    

    触发事件的唯一方式是您在输入后失去对文本框的关注。

    需要考虑的要点: 这将导致回发,因此 Ajax 可能是保持用户体验良好的好方法。 您需要确保将 DataBind() 包装在 if (!IsPostBack) 中

    希望这会有所帮助!

    【讨论】:

    • 我可以毫无问题地触发该事件(它的调用方式与您描述的完全一样)。我的问题是引用“发件人”文本框所在的行。
    【解决方案2】:

    实际上,我通过在表中添加一个自动编号列来解决这个问题,并使用它的值来确定表中行的位置,然后使用它的值来影响数据网格中的相应行。 如原始问题所述,我现在只是更改行的颜色,而不是将该行中的值添加到数组中。

    public void txtPrice_TextChanged(object sender, EventArgs e)
    {
        TextBox txtPrice = (TextBox)sender;
        DataGridItem myItem = (DataGridItem)txtPrice.Parent.Parent;
        markRows(myItem, true);
    }
    
    public void markRows(DataGridItem myItem, bool toSave)
    {
        // Prepeare to save this record?
        CheckBox thisSave = (CheckBox)myItem.FindControl("chkSave");
        thisSave.Checked = toSave;
        // Establish the row's position in the table
        Label sNo = (Label)myItem.FindControl("SNo");
        int rowNum = Convert.ToInt32(sNo.Text) - 1;
        CheckBox rowSave = (CheckBox)grid.Items[rowNum].FindControl("chkSave");
    
        // Update background color on the row to remove/add highlight 
        if (rowSave.Checked == true)
            grid.Items[rowNum].BackColor = System.Drawing.Color.GreenYellow;
        else
        {
            Color bgBlue = Color.FromArgb(212, 231, 247);
            grid.Items[rowNum].BackColor = bgBlue;
            // some code here to refresh data from table?
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多