Reputation: 1
I have a textbox for the Amount and I would like the following statement to display it.
Below are my code:
<!--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>
Code Behind:
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();
}
Thanks!
Upvotes: 0
Views: 173
Reputation: 98740
If your query is okey, just use ExecuteScalar
to get this value and assign your textbox's Text
property. You don't need to use ExecuteReader
for that.
var sum = cmd.ExecuteScalar();
txtBudget.Text = sum.ToString();
Also use using
statement to dispose your connection and command like;
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();
}
}
Upvotes: 3
Reputation: 460048
You just need to use 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();
}
}
another approach is using ExecuteScalar
if you just select a single value(as shown by Soner).
Upvotes: 2