我有Amount的文本框,我希望以下语句来显示它。
以下是我的代码:
<!--Amount-->
<div class="form-group">
<label class="control-label col-lg-4">
Amount</label>
<div class="col-lg-8">
<asp:TextBox ID="txtBudget" runat="server" class="form-control" AutoPostBack="True" />
</div>
</div>
代码背后:
void GetTotalAmount()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT SUM(Materials.SellingPrice + Equipments.Price + Resource_Vehicles.Cost + Contractors.Rate) " +
"FROM ProjectTasks INNER JOIN Resource_Contractors ON ProjectTasks.TaskID = Resource_Contractors.TaskID INNER JOIN " +
"Resource_Equipments ON ProjectTasks.TaskID = Resource_Equipments.TaskID INNER JOIN Resource_Materials ON ProjectTasks.TaskID = Resource_Materials.TaskID INNER JOIN " +
"Resource_Vehicles ON ProjectTasks.TaskID = Resource_Vehicles.TaskID INNER JOIN Contractors ON Resource_Contractors.ContractorID = Contractors.ContractorID INNER JOIN " +
"Materials ON Resource_Materials.MaterialID = Materials.MaterialID INNER JOIN Equipments ON Resource_Equipments.EquipmentID = Equipments.EquipmentID INNER JOIN " +
"Vehicles ON Resource_Vehicles.VehicleID = Vehicles.VehicleID WHERE ProjectTasks.TaskID=@TaskID";
SqlDataReader dr = cmd.ExecuteReader();
con.Close();
}
谢谢!
答案 0 :(得分:3)
如果您的查询非常简单,只需使用ExecuteScalar
获取此值并指定文本框的Text
属性即可。您不需要使用ExecuteReader
。
var sum = cmd.ExecuteScalar();
txtBudget.Text = sum.ToString();
还可以使用using
statement来处理您的连接和命令,如;
void GetTotalAmount()
{
using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "...";
con.Open();
var sum = cmd.ExecuteScalar();
txtBudget.Text = sum.ToString();
}
}
答案 1 :(得分:2)
您只需使用SqlDataReader.GetDouble
:
using (var dr = cmd.ExecuteReader()) // use using for everything implementing IDisposable, also connection
{
if (dr.HasRows)
{
dr.Read(); // advances reader to first record
txtBudget.Text = dr.GetDouble(0).ToString();
}
}
如果您只选择一个值(如Soner所示),则另一种方法是使用ExecuteScalar
。