当另一个用户控件中的标签文本发生更改时,更新另一个用户控件中控件的文本

时间:2017-03-18 10:05:37

标签: c# asp.net

我使用usercontrol在页面左侧显示标签文本,另一个用户控件显示内容页面,当内容页面上的字段文本发生变化时,我需要在标签上更新相同的状态在左边的菜单usercontrol上。

我用过:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),"ChangeLabelText", script, false) 

要更改左侧控件上的文本,与此关联的javascript将被执行,但即使在页面刷新后更新内容页面上的文本,标签仍会显示旧文本。但是,它会在整个页面刷新时显示新的更新文本。

请提出解决此问题的方法。

1 个答案:

答案 0 :(得分:0)

如果页面上有两个UserControl,并且想要从第一个控件中的代码更新第二个控件中的Label,则需要使用FindControl

//find the other control in the parent
Control control = Parent.FindControl("WebUserControl2") as Control;

//find the label in that control
Label label = control.FindControl("Label1") as Label;

//update the label
label.Text = "Updated from another control";

<强>更新

如果您想使用javascript进行更新,则必须确保发送正确的ID

ScriptManager.RegisterStartupScript(Page, GetType(), "changeLabel", "changeLabel('WebUserControl2_Label1', 'Updated with JS')", true);

和javscript函数

<script type="text/javascript">
    function changeLabel(id, text) {
        document.getElementById(id).innerHTML = text;
    }
</script>
相关问题