ASP.NET에서 제어 기능을 찾는 더 좋은 방법
저는 복잡한 asp.net 양식을 가지고 있으며, 한 양식에 50에서 60개의 필드가 있습니다.MultiviewMultiView 내부에는GridView그리고 GridView 안에는 여러 개가 있습니다.CheckBoxes.
현재 저는 의 체인을 사용하고 있습니다.FindControl()메서드 및 하위 ID를 검색합니다.
이제, 제 질문은 ASP에서 중첩된 컨트롤을 찾을 수 있는 다른 방법/솔루션이 있는지 여부입니다.그물.
특정 유형의 컨트롤을 찾고 있다면 다음과 같은 반복 루프를 사용할 수 있습니다. - http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx
다음은 지정된 유형의 모든 컨트롤을 반환하는 예제입니다.
/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control
{
private readonly List<T> _foundControls = new List<T>();
public IEnumerable<T> FoundControls
{
get { return _foundControls; }
}
public void FindChildControlsRecursive(Control control)
{
foreach (Control childControl in control.Controls)
{
if (childControl.GetType() == typeof(T))
{
_foundControls.Add((T)childControl);
}
else
{
FindChildControlsRecursive(childControl);
}
}
}
}
평소처럼 늦게.여전히 이 문제에 관심이 있는 사람이 있다면 관련 SO 질문과 답변이 많이 있습니다.이 문제를 해결하기 위한 My 버전의 재귀 확장 방법:
public static IEnumerable<T> FindControlsOfType<T>(this Control parent)
where T : Control
{
foreach (Control child in parent.Controls)
{
if (child is T)
{
yield return (T)child;
}
else if (child.Controls.Count > 0)
{
foreach (T grandChild in child.FindControlsOfType<T>())
{
yield return grandChild;
}
}
}
}
강조 표시된 모든 솔루션은 재귀(성능 비용이 많이 드는)를 사용하고 있습니다.재귀를 방지하는 더 깨끗한 방법은 다음과 같습니다.
public T GetControlByType<T>(Control root, Func<T, bool> predicate = null) where T : Control
{
if (root == null) {
throw new ArgumentNullException("root");
}
var stack = new Stack<Control>(new Control[] { root });
while (stack.Count > 0) {
var control = stack.Pop();
T match = control as T;
if (match != null && (predicate == null || predicate(match))) {
return match;
}
foreach (Control childControl in control.Controls) {
stack.Push(childControl);
}
}
return default(T);
}
FindControl은 중첩된 컨트롤 내에서 재귀적으로 검색하지 않습니다.NamigContainer가 FindControl을 호출하는 컨트롤인 컨트롤만 찾습니다.
ASP에 대한 이유가 있습니다.Net은 기본적으로 중첩된 컨트롤을 재귀적으로 조사하지 않습니다.
- 성능
- 오류 방지
- 재사용 가능성
재사용 가능성을 위해 그리드 보기, 양식 보기, 사용자 컨트롤 등을 다른 사용자 컨트롤 내부에 캡슐화하는 것을 고려해 보십시오.페이지에 모든 논리를 구현하고 반복 루프를 사용하여 이러한 컨트롤에 액세스했다면 이를 다시 요인화하기가 매우 어려울 것입니다.이벤트 핸들러(예: GridView의 RowDataBound)를 통해 논리 및 액세스 방법을 구현한 경우 훨씬 간단하고 오류가 발생하기 쉽습니다.
제어 시 작업 관리
기본 클래스에서 아래 클래스를 만듭니다.클래스 모든 컨트롤을 가져오는 방법:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
데이터베이스에서:DTActions(DTActions)의 DATAset(DTActions)에서 동적으로 사용할 수 있는 모든 작업 ID(예: divAction1, divAction2...)를 가져옵니다.
Asx에서: HTML Put Action(버튼, 앵커 등)을 divor span에 넣고 id를 지정합니다.
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
INCS: 페이지에서 다음 기능을 사용합니다.
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
지정된 술어와 일치하는 모든 컨트롤을 재귀적으로 찾습니다(루트 컨트롤 포함 안 함).
public static IEnumerable<Control> FindControlsRecursive(this Control control, Func<Control, bool> predicate)
{
var results = new List<Control>();
foreach (Control child in control.Controls)
{
if (predicate(child))
{
results.Add(child);
}
results.AddRange(child.FindControlsRecursive(predicate));
}
return results;
}
용도:
myControl.FindControlsRecursive(c => c.ID == "findThisID");
저는 제어 사전을 만들기로 결심했습니다.유지 관리가 어려워 재귀 찾기 컨트롤()보다 더 빨리 실행될 수 있습니다.
protected void Page_Load(object sender, EventArgs e)
{
this.BuildControlDics();
}
private void BuildControlDics()
{
_Divs = new Dictionary<MyEnum, HtmlContainerControl>();
_Divs.Add(MyEnum.One, this.divOne);
_Divs.Add(MyEnum.Two, this.divTwo);
_Divs.Add(MyEnum.Three, this.divThree);
}
그리고 내가 OP의 질문에 대답하지 않은 것에 대해 모욕을 당하기 전에...
Q: 이제 제 질문은 ASP에서 중첩된 컨트롤을 찾을 수 있는 다른 방법/솔루션이 있는지 여부입니다.NET? A: 네, 애초에 검색할 필요는 없습니다.이미 알고 있는 것을 검색하는 이유는 무엇입니까?알려진 물체를 참조할 수 있는 시스템을 구축하는 것이 좋습니다.
https://blog.codinghorror.com/recursive-pagefindcontrol/
Page.FindControl("DataList1:_ctl0:TextBox3");
OR
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
다음 예제에서는 Button1_Click 이벤트 핸들러를 정의합니다.호출되면 이 핸들러는 FindControl 메서드를 사용하여 포함 페이지에서 TextBox2의 ID 속성을 가진 컨트롤을 찾습니다.컨트롤이 발견되면 상위 속성을 사용하여 상위 컨트롤이 결정되고 상위 컨트롤의 ID가 페이지에 기록됩니다.TextBox2를 찾을 수 없는 경우, "Control Not Found"가 페이지에 기록됩니다.
private void Button1_Click(object sender, EventArgs MyEventArgs)
{
// Find control on page.
Control myControl1 = FindControl("TextBox2");
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}
}
언급URL : https://stackoverflow.com/questions/4955769/better-way-to-find-control-in-asp-net
'codememo' 카테고리의 다른 글
| 프로젝트 폴더가 없는 git clone (0) | 2023.08.16 |
|---|---|
| Swift에서 날짜를 밀리초 단위로 표시하고 다시 날짜로 표시합니다. (0) | 2023.08.16 |
| 새로운 iTunes Connect 사이트에서 앱 빌드를 삭제하는 방법은 무엇입니까? (0) | 2023.08.11 |
| 계층화된 열차/시험 분할(scikit (0) | 2023.08.11 |
| "이미지가 중지된 컨테이너에서 사용되고 있습니다" 오류 (0) | 2023.08.11 |