撰寫網頁程式時,有時會需要抓取控制項填入值或更改設定,可以用Page.FindControl()來抓取控制項....
撰寫網頁程式時,有時會需要抓取控制項填入值或更改設定,可以用Page.FindControl()來抓取控制項....
基本語法範例:
//宣告控制項型別及名稱 = ( 強制轉換型別) FindControl(尋找的控制項名稱)
Label lblin = (Label)FindControl(lblSPEC);
Label lblin = (Label)FindControl(lblSPEC);
但是有時候需要使用多個控制項,這時候在設計介面時就很重要了,最好在設計時命名控制項的ID時加入有規則的數字,再以邏輯方法來找出控制項;這樣子一方面不用一個一個找,造成程式碼冗長,修改時費時不便;另一方面也讓程式較有效率.
範例:
/// <summary>
/// 清空Panel
/// </summary>
void ClearPanel()
{
//以For迴圈在控制項名稱帶入變數逐個尋找符合名稱的控制項
for (int i = 0; i <= 7; i++)
{
Panel pnl = (Panel)FindControl("Panel" + i.ToString());
if (pnl.Visible == true)
{
//找到控制項後判斷名稱若符合條件執行.....
switch (pnl.ID)
{
case "Panel0":
tbAM.Text = "";
lblAV.Text = "";
lblAR.Text = "";
ddlATF.SelectedIndex = 0;
lblAS.Text = "";
break;
case "Panel1":
tbBM.Text = "";
lblBV.Text = "";
lblBR.Text = "";
ddlBTF.SelectedIndex = 0;
lblBS.Text = "";
break;
case "Panel2":
tbCM.Text = "";
lblCV.Text = "";
lblCR.Text = "";
ddlCTF.SelectedIndex = 0;
lblCS.Text = "";
break;
case "Panel3":
tbDM.Text = "";
lblDV.Text = "";
lblDR.Text = "";
ddlDTF.SelectedIndex = 0;
lblDS.Text = "";
break;
case "Panel4":
tbEM.Text = "";
lblEV.Text = "";
lblER.Text = "";
ddlETF.SelectedIndex = 0;
lblES.Text = "";
break;
case "Panel5":
tbFM.Text = "";
lblFV.Text = "";
lblFR.Text = "";
ddlFTF.SelectedIndex = 0;
lblFS.Text = "";
break;
case "Panel6":
tbGM.Text = "";
lblGV.Text = "";
lblGR.Text = "";
ddlGTF.SelectedIndex = 0;
lblGS.Text = "";
break;
case "Panel7":
tbHM.Text = "";
lblHV.Text = "";
lblHR.Text = "";
ddlHTF.SelectedIndex = 0;
lblHS.Text = "";
break;
}
pnl.Visible = false;
}
}
}
/// 清空Panel
/// </summary>
void ClearPanel()
{
//以For迴圈在控制項名稱帶入變數逐個尋找符合名稱的控制項
for (int i = 0; i <= 7; i++)
{
Panel pnl = (Panel)FindControl("Panel" + i.ToString());
if (pnl.Visible == true)
{
//找到控制項後判斷名稱若符合條件執行.....
switch (pnl.ID)
{
case "Panel0":
tbAM.Text = "";
lblAV.Text = "";
lblAR.Text = "";
ddlATF.SelectedIndex = 0;
lblAS.Text = "";
break;
case "Panel1":
tbBM.Text = "";
lblBV.Text = "";
lblBR.Text = "";
ddlBTF.SelectedIndex = 0;
lblBS.Text = "";
break;
case "Panel2":
tbCM.Text = "";
lblCV.Text = "";
lblCR.Text = "";
ddlCTF.SelectedIndex = 0;
lblCS.Text = "";
break;
case "Panel3":
tbDM.Text = "";
lblDV.Text = "";
lblDR.Text = "";
ddlDTF.SelectedIndex = 0;
lblDS.Text = "";
break;
case "Panel4":
tbEM.Text = "";
lblEV.Text = "";
lblER.Text = "";
ddlETF.SelectedIndex = 0;
lblES.Text = "";
break;
case "Panel5":
tbFM.Text = "";
lblFV.Text = "";
lblFR.Text = "";
ddlFTF.SelectedIndex = 0;
lblFS.Text = "";
break;
case "Panel6":
tbGM.Text = "";
lblGV.Text = "";
lblGR.Text = "";
ddlGTF.SelectedIndex = 0;
lblGS.Text = "";
break;
case "Panel7":
tbHM.Text = "";
lblHV.Text = "";
lblHR.Text = "";
ddlHTF.SelectedIndex = 0;
lblHS.Text = "";
break;
}
pnl.Visible = false;
}
}
}