![](/img/trans.png)
[英]Difference between “Convert.ToString(Nullable<int>)” and “Nullable<int>.ToString()”?
[英]I can't convert an int and a float with convert.ToString() to string
我的表單中有2個控件,一個是int,另一個是float,我嘗試使用“ Convert.toString()”方法進行轉換,但是它沒有用,並且我一直都得到null值,這是我的代碼:
string req = "select coef from amortissement where id_amort =@p";
textBox4.Text =Convert.ToString(GetRecordsetValue(req, textBox1.Text) as String)
req = "select Plan from amortissement where id_amort =@p";
textBox3.Text =Convert.ToString(GetRecordsetValue(req, textBox1.Text) as String);
這是GetRecordsetValue方法:
private Object GetRecordsetValue(string req, string sValParam)
{
// ExecuteScalar est optimisée pour récupérer une seule valeur
SqlCommand cmd = null;
try
{
cmd = new SqlCommand(req, con);
cmd.Parameters.AddWithValue("@p", sValParam);
return cmd.ExecuteScalar();
}
catch
{
return String.Empty;
}
finally
{
cmd.Dispose();
}
}
感謝幫助
如果您的查詢找不到與WHERE條件匹配的記錄,則GetRecordsetValue
的代碼將返回NULL。 返回的空值傳遞回Convert.ToString(),這將引發異常
string req = "select coef from amortissement where id_amort =@p";
object result = GetRecordsetValue(req, textBox1.Text);
if(result != null)
{
textBox4.Text = Convert.ToString(result);
}
else
{
// and/or a message to the user to correct its inputs.
textBox4.Text = "";
}
還存在在GetRecordsetValue
內部傳遞值的問題。 該值作為字符串傳遞,並作為字符串數據類型添加到參數集合內。 如果字段id_amort
不是字符串(從它的名稱看來),那么您的查詢很可能找不到記錄。
我建議創建不同的GetRecordsetValue重載。 以整數為例的一個
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.