我希望能够在标签上显示余额,而我的代码无效。这是我到目前为止的代码:
SqlDataReader readdata;
{
sqlCommandbalance.Connection.Open();
sqlCommandbalance.Parameters["@accountID"].Value = show.accoundID;
readdata = sqlCommandbalance.ExecuteReader();
string balanceDB = null;
while (readdata.Read())
{
balanceDB = readdata["balance"].ToString();
}
sqlCommandbalance.Connection.Close();
balanceShow.Text += " " + balanceDB.ToString();
}
在这一行 - balanceShow.Text += " " + balanceDB.ToString();
收到错误,指出对象引用未设置为对象的实例。
答案 0 :(得分:10)
如果数据阅读器不包含任何行,则balanceDB.ToString()
为空时,您正在调用balanceDB
。
请注意balanceDB.ToString()
是多余的,因为balanceDB
已经是一个字符串。只需取出ToString
电话。
您还可以将balanceDB初始化为
string balanceDB = "";
答案 1 :(得分:6)
最初设置balanceDB = null;
。
如果未找到任何数据,则不会对balanceDB
循环中的while
进行任何分配,因此它将保持未定义状态。
答案 2 :(得分:6)
这是因为string balanceDB = null;
将其设置为string balanceDB = string.Empty;
,您应该没问题
答案 3 :(得分:0)
Readdata.read可能返回false,使得while从不运行。因此,balanceDB仍为空。
答案 4 :(得分:0)
看起来您的查询返回一个空集。您应该在设置balanceShow.Text之前检查它:
if (balanceDB != null) {
balanceShow.Text += " " + balanceDB.ToString();
} else {
// tell the user that id: show.accoundID has no balance
}
答案 5 :(得分:0)
可能你的代码在dataRader中撤回null,结果你在balanceDB上修了一个null值。我建议你做这样的事情:
public static string GetBalance() {
string result = string.Emtpy;
using (var connection = /* Build your SqlConnection */) {
using (var cmd = new SqlCommand("your select command here", connection) {
try
{
connection.Open();
// you don't need a reader to take just a single value
object value = cmd.ExecuteScalar();
if (value != null)
result = value.ToString();
}
catch(Exception ex)
{
/* you've got an error */
}
finally
{
connection.Close();
}
}
}
return result;
}
并在您的信息页中:
string balance = GetBalance();
if (!string.IsNullOrEmpty(balance))
balanceShow.Text += string.Contat(" ", balance);
如果你想连接balanceShow标签,请使用'+ ='运算符,而不是你只需'='。
PS:对不起我的英文!