zoukankan      html  css  js  c++  java
  • ListView中获取ClientID的一个小问题

    今天在VS2010中使用ListView控件的时候,遇到了这么一个问题:在ItemCreated事件中无法找到在ListView中的控件的ClientID,准确说是得到一个错误的ClientID

    引发事件的代码如下:

    protected void ListView1_ItemCreated(object sender, ListViewItemEventArgs e)
    {
         if (e.Item.ItemType == ListViewItemType.InsertItem)
         {
              TextBox txt_name = (TextBox)e.Item.FindControl("nameTextBox");
              txt_name.Attributes["haha"] = txt_name.ClientID;
         }
    }
    
    结果得到的ClientID就是错误的,它会在前面加个ctrl3_,但真实的ClientID是ListView1_nameTextBox

    解决这个问题方案是可以在ItemDataBound事件中获取正确的ClientID值或者在PreRender事件中获取客户端ID也可以,具体解决方案和原因参看:http://connect.microsoft.com/VisualStudio/feedback/details/328680/problem-accessing-controls-clientid-on-asp-net-listviews-itemcreated

    由于我的界面InsertItem类型是没有数据绑定的,所以我采用在PreRender事件中获取的方法:

    protected void ListView1_PreRender(object sender, EventArgs e)
    {
         TextBox txt_age =(TextBox)FindControl("ageTextBox", ListView1.Controls);
         if(txt_age!=null)
              txt_age.Attributes["haha"] = txt_age.ClientID;
    }
    
    其中FindControl为自定义静态函数:

    public static Control FindControl(string controlId, ControlCollection controls) {
    foreach (Control control in controls) {
        if (control.ID == controlId)
         return control;
        if (control.HasControls()) {
         Control nestedControl = FindControl(controlId, control.Controls);
         if (nestedControl != null)
            return nestedControl;
         }
    }
    return null;
    }
    
    这样,结果就正确了。

  • 相关阅读:
    Merge Two Sorted Lists
    4Sum
    Letter Combinations of a Phone Number
    3Sum Closest
    3Sum
    Longest Common Prefix
    Roman to Integer
    Integer to Roman
    Container With Most Water
    Regular Expression Matching
  • 原文地址:https://www.cnblogs.com/heqichang/p/1829617.html
Copyright © 2011-2022 走看看