【问题标题】:How to change value of TemplateField dynamically?如何动态更改 TemplateField 的值?
【发布时间】:2010-11-10 21:31:28
【问题描述】:

我有一个 GridView,我想在它被选中时刷新一行(而不是整个网格)。当网格选择的索引发生变化时,我尝试为每个GridView.SelectedRow.Cells 更改Text 属性。它似乎适用于DataField,但不适用于TemplateField。对于TemplateField,我得到了奇怪的结果 - 所选行的值正确更改,但是当我选择另一行时,先前选择的行的TemplateField 的值变为空白。简要说明:

1. Nothing selected
--------------------------
id          template_field
--------------------------
 1          value_1
 2          value_2

2. First record selected
--------------------------
id          template_field
--------------------------
 1          updated_value_1
 2          value_2

3. Second record selected
--------------------------
id          template_field
--------------------------
 1          [blank!]
 2          updated_value_2

最终,除了选中的每条记录,我都会得到空白template_field。更改 TemplateField 文本的正确方法是什么?

【问题讨论】:

    标签: asp.net gridview templatefield


    【解决方案1】:

    尝试将 TextBox 控件添加到您的模板中,并更改 it 而不是单元格内容。您应该可以通过以下方式获得它:

    TextBox tb = GridView.SelectedRow.Cells[0].Controls[0] as TextBox;
    if(tb != null)
       tb.Text = newValue;
    

    【讨论】:

    • 我会试试的。我已经尝试过更改TextControls[0],但是这个属性是只读的,所以它不起作用。
    • 但是您是否在模板字段中添加了 TextBox 控件?这样您就可以尝试更改 TextBox 的内容(它有自己的视图状态,因此应该记住更改)。
    • 我现在正在尝试...感谢您的想法。
    • 非常感谢。它确实有效。顺便说一句,它不一定是 TextBox,它也可以与 Label 一起使用(我不需要它是可编辑的)。
    猜你喜欢
    • 2015-01-06
    • 2021-03-27
    • 2011-11-08
    • 2020-12-12
    • 2017-11-03
    • 2013-01-26
    • 2017-07-06
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多