遍历获取ASP.NET页面控件的名称及值

逛csdn的时候碰见有人在求助这个问题,特分享一下经验。
如果直接用Page.Control 获取的到只是最顶层的页面元素,而真正的拖拉放上去的文本框或Label之类的控件,还隐藏在这些顶层页面元素的里面,所以需要再次遍历。
函数及使用方法如下,结果保存在这里选择了HashTable的方式。

None.gif protected   void  Page_Load( object  sender, EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        getAllControlValue(
this);
ExpandedBlockEnd.gif    }

None.gif
None.gif    Hashtable getAllControlValue( 
object  PageOrUserControl )
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        Hashtable rtn 
= new Hashtable();
InBlock.gif
InBlock.gif        
foreach (Control ctr in (PageOrUserControl as Page).Controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            getControlValue(ctr, rtn);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
return rtn;
ExpandedBlockEnd.gif    }

None.gif
None.gif    
void  getControlValue(Control ctrIn,Hashtable ht)
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif {
InBlock.gif        
foreach (Control ctr in ctrIn.Controls)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Type controlType 
= ctr.GetType();
InBlock.gif
InBlock.gif            
switch (controlType.ToString())
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
case "System.Web.UI.WebControls.TextBox":
InBlock.gif                    TextBox controlTextBoxObj 
= (TextBox)ctr;
InBlock.gif                    
string controlTextBoxName = controlTextBoxObj.ID;
InBlock.gif                    
string controlTextBoxValue = controlTextBoxObj.Text;
InBlock.gif                    ht.Add(controlTextBoxName, controlTextBoxValue);
InBlock.gif                    
break;
InBlock.gif                
case "System.Web.UI.WebControls.Label":
InBlock.gif                    Label controlLabelObj 
= (Label)ctr;
InBlock.gif                    
string controlLabelName = controlLabelObj.ID;
InBlock.gif                    
string controlLabelValue = controlLabelObj.Text;
InBlock.gif                    ht.Add(controlLabelName, controlLabelValue);
InBlock.gif                    
break;
InBlock.gif                
//case "其他类型":
InBlock.gif                
//    其它类型 controlTextBoxObj = (其它类型)ctr;
InBlock.gif                
//    string controlTextBoxName = controlTextBoxObj.ID;
InBlock.gif                
//    string controlTextBoxValue = controlTextBoxObj.Text;
InBlock.gif                
//    ht.Add(controlTextBoxName, controlTextBoxValue);
InBlock.gif                
//    break;
InBlock.gif
                default:
InBlock.gif                    
break;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedBlockEnd.gif    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值