3
int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
compliling錯誤後輸入字符串的不正確的格式輸入字符串的不正確的格式在DataList控件
int id = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
compliling錯誤後輸入字符串的不正確的格式輸入字符串的不正確的格式在DataList控件
當我們使用Convert.ToInt32
與string
輸入,它只會返回有效結果(並非例外)如果string
的所有字符都是總數值限制爲int.MinValue
至int.MaxValue
的數字。
首先,以確保輸入是在string
格式,更改DataList1.DataKeys[e.Item.ItemIndex]
與DataList1.DataKeys[e.Item.ItemIndex].ToString()
,像這樣
string itemStr = DataList1.DataKeys[e.Item.ItemIndex].ToString();
;其次,以確保string
是正確的格式,嘗試分析它使用int.TryParse
。只有當參數傳遞int.TryParse
你是安全執行Convert.ToInt32
它
int id;
if (int.TryParse(itemStr, out id)){
//do something with id
} else {
//Parse fails, do something
}
看看是否有幫助。
在[e.Item.ItemIndex]之後添加.ToString()。所以它看起來像這樣:[e.Item.ItemIndex] .ToString() – TuukkaX