![](/img/trans.png)
[英]is ToInt32() an extension method in C#? specially Convert.ToInt32()
[英]FormView FindControl not able to convert ToInt32
我有一個Cust_Result類,它接受一個整數參數。
所以在我的主頁上加載時我綁定一個formview來顯示我檢索的數據。 現在我想提取我的“id”標簽的值並將其分配給一個變量,我可以傳遞給我的Cust_Result類,但是我一直收到這個錯誤
“無法將'System.Web.UI.WebControls.Label'類型的對象強制轉換為'System.IConvertible'。”
我假設它是因為我試圖將字符串值發送到想要一個整數值的參數,但我不確定如何進行轉換。
我的代碼
int cust;
cust = (Convert.ToInt32(FormView1.Row.FindControl("ID")));
你需要一個字符串來轉換,這是Label.Text
屬性(而不僅僅是Label)。
我將它分為兩步:
Label lbl = FormView1.Row.FindControl("ID") as Label;
// option to bail out when lbl == null
cust = Convert.ToInt32(lbl.Text);
首先將控件轉換為Label
var label = (Label)FormView1.Row.FindControl("ID");
然后你可以獲得標簽中的值:
var cust = int.Parse(label.Text);
仔細查看編譯器錯誤 - 它沒有說明關於string
和int
任何內容 - 它正在談論IConvertible
和Label
- 盡管它提到Label
而不是Control
這一事實表明這不是你實際發布的代碼。 Convert.ToInt32
不知道如何處理Control
或Label
- 在這種情況下,我相信你想要標簽的文本 ,所以我寫這個:
Label label = (Label) FormView1.Row.FindControl("ID");
// Potentially check for "label" being null here, i.e. the control wasn't found
int cust = Convert.ToInt32(label.Text);
這個值來自哪里並不完全清楚,但你可能也想考慮使用int.TryParse
而不是Convert.ToInt32
。
我還注意到Cust_Result
是一個非傳統的名字 - 試着:
CustomerResult
並沒有真正解釋它的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.