alt text http://i43.tinypic.com/5l8op0.jpg錯誤:在Linq中,用戶代碼未能處理FormatException如何解決?
望請低於這個代碼扔給我:出現FormatException是未處理由用戶代碼
代碼:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
我怎麼可以重寫LINQ查詢?
alt text http://i43.tinypic.com/5l8op0.jpg錯誤:在Linq中,用戶代碼未能處理FormatException如何解決?
望請低於這個代碼扔給我:出現FormatException是未處理由用戶代碼
代碼:
satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());
我怎麼可以重寫LINQ查詢?
您在查詢中調用了ToString
而不是單個結果。即使您可能希望只有一個值符合您的查詢,它也不會只返回一個值。您必須指示它使用Single
,First
,Last
或這些也會返回默認值(SingleOrDefault
,FirstOrDefault
,LastOrDefault
)的變體。
爲避免發生異常,可以將其更改爲使用Decimal.TryParse
,或者如果LINQ查詢返回的內容不能正確解析,則可以將代碼更改爲使用默認值。我會推薦前者或組合。
請注意,在以下示例中,我添加了對SingleOrDefault的呼叫。這確保只有一個值被解析,即使沒有找到值,並且如果有多個結果,我們會得到一個異常(即強制我們得到的結果完全是零或一個查詢結果)。
decimal parsedValue;
if (Decimal.TryParse(
genSatisctx
.Urun
.Where(o => o.ID == UrunID)
.Select(o=>o.Kdv)
.SingleOrDefault()
.ToString(), out parsedValue))
{
satis.KDV = parsedValue;
}
你調用上IQueryable<T>
ToString()
- 你是怎麼想到的字符串是什麼?這不太可能是任何可以解析爲十進制數的東西!
我的猜測是你想打電話給First()
或Single()
,但是如果沒有更多的信息,我們就無法真正分辨出來。什麼是o.Kdv
的類型?
我懷疑你要麼需要:
satis.KDV = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
或
string kdvString = (from o in genSatisctx.Urun
where o.ID == UrunID
select o.Kdv).First();
decimal kdv;
if (decimal.TryParse(kdvString, out kdv))
{
satis.KDV = kdv;
}
else
{
// What do you want to do if it's not valid?
}
當我使用調試模式我看到的數據是更新,當鼠標懸停,這個方法結束後(它顯示此消息[輸入的字符串格式不正確]
/* protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
SqlDataSource2.Update();
}
catch (Exception j)
{
j.Message.ToString();
}
}
/* }
你需要[編輯]並修改你的格式,否則你會得到downvoted,你不會得到任何答案。 – Will 2012-07-02 20:58:38
如果找不到值,則會在ToString調用中引發NullPointerException。 – 2010-04-07 14:54:37
@Jon:這不是依賴於什麼'o.Kdv'?如果它是一個十進制或其他數字,不會默認只是0? – 2010-04-07 15:04:39