Asked by:
calculations in grid control.....

Question
-
User-318386396 posted
Ihave a grid view in which edit insert update delete each work is ok but now i have to do calculations in my grid i.e i have to calculate value from one field of grid and on that basis calculate percentages,additions,subtraction and show data on the next field e.g there are two fields percentage,total sum
now from percentage and a given value i calculate total sum and show next to percentage.this all work should also be done while editing the data in grid view.Is this all possible ?any solutions....??
Thursday, November 20, 2008 8:21 AM
All replies
-
User-1760427068 posted
You can do work on data in the table using the code behind page. For work on a code behind page, do you have a preference of C# or VB?
With what program are you working? (Visual Web Developer 2008 Expression Edition, Visual Studio 2008, etc.)
Since you mention working with a gridview I assume you already have a table in a database. For simplicity may I suggest a small table with two columns containing integers?
For output it can show the table data in the first two columns in the third column. Have you done work with CSS? I'll assume not and do the formatting of output with <table>,<tr>,<td>. This can be changed to CSS if you prefer CSS.
If I don't hear from you for a while I'll go ahead and construct some examples using C#. For this project it won't be hard to convert C# over to VB.
Table
id,Number1,Number2
1,2,3
2,3,4
3,4,5
4,9,10
SQL statements to generate the table and put the data into it.
CREATE TABLE Numbers
(id smallint IDENTITY(1,1) PRIMARY KEY,
number1 int NOT NULL,
number2 int NOT NULL)INSERT INTO Numbers (number1, number2) VALUES ('2','3')
INSERT INTO Numbers (number1, number2) VALUES ('3','4')
INSERT INTO Numbers (number1, number2) VALUES ('4','5')
INSERT INTO Numbers (number1, number2) VALUES ('9','10')-Larry
Thursday, November 20, 2008 8:32 PM -
User-1760427068 posted
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Numbers.aspx.cs" Inherits="Numbers" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Numbers</title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="PercentagesButton" runat="server" Text="Percentages" onclick="PercentagesButton_Click" /> <asp:Button ID="AdditionButton" runat="server" Text="Addition" onclick="AdditionButton_Click" /> <asp:Button ID="SummationButton" runat="server" Text="Summation" onclick="SummationButton_Click" /> <br /><br /><br /> <div id="theresultsdiv" runat="server" /> </form> </body> </html>
Thursday, November 20, 2008 9:45 PM -
User-1760427068 posted
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; // This was needed for SqlConnection to function using System.Configuration; // This was needed for ConfigurationManager to function using System.Data; // This was needed for CommandType to function public partial class Numbers : System.Web.UI.Page { double firstnumber; // firstnumber and secondnumber are defined above the subroutines because double secondnumber; // they will be used in all subroutines protected void Page_Load(object sender, EventArgs e) { theresultsdiv.InnerHtml = "Click any of the above buttons."; } protected void PercentagesButton_Click(object sender, EventArgs e) { theresultsdiv.InnerHtml = "<b>Percentages</b>"; // after this, all others will be += to add on to what is already there theresultsdiv.InnerHtml += "<table border=1>"; double thepercentage; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT number1, number2 FROM Numbers"; cmd.CommandType = CommandType.Text; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { firstnumber = Convert.ToDouble(reader["number1"]); secondnumber = Convert.ToDouble(reader["number2"]); thepercentage = 100 * firstnumber / secondnumber; theresultsdiv.InnerHtml += "<tr><td>" + firstnumber.ToString() + "</td>"; theresultsdiv.InnerHtml += "<td>" + secondnumber.ToString() + "</td>"; theresultsdiv.InnerHtml += "<td>" + thepercentage.ToString("N4") + "</td></tr>"; } reader.Close(); conn.Close(); theresultsdiv.InnerHtml += "</table>"; } protected void AdditionButton_Click(object sender, EventArgs e) { theresultsdiv.InnerHtml = "<b>Addition</b>"; // after this, all others will be += to add on to what is already there theresultsdiv.InnerHtml += "<table border=1>"; double thepercentage; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT number1, number2 FROM Numbers"; cmd.CommandType = CommandType.Text; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { firstnumber = Convert.ToDouble(reader["number1"]); secondnumber = Convert.ToDouble(reader["number2"]); thepercentage = firstnumber + secondnumber; theresultsdiv.InnerHtml += "<tr><td>" + firstnumber.ToString() + "</td>"; theresultsdiv.InnerHtml += "<td>" + secondnumber.ToString() + "</td>"; theresultsdiv.InnerHtml += "<td>" + thepercentage.ToString("N3") + "</td></tr>"; } reader.Close(); conn.Close(); theresultsdiv.InnerHtml += "</table>"; } protected void SummationButton_Click(object sender, EventArgs e) { { theresultsdiv.InnerHtml = "<b>Summation</b>"; // after this, all others will be += to add on to what is already there theresultsdiv.InnerHtml += "<table border=1>"; int column1sum; int column2sum; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT number1, number2 FROM Numbers"; cmd.CommandType = CommandType.Text; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { firstnumber = Convert.ToDouble(reader["number1"]); secondnumber = Convert.ToDouble(reader["number2"]); theresultsdiv.InnerHtml += "<tr><td>" + firstnumber.ToString() + "</td>"; theresultsdiv.InnerHtml += "<td>" + secondnumber.ToString() + "</td></tr>"; } reader.Close(); conn.Close(); theresultsdiv.InnerHtml += "</table>"; conn.Open(); cmd.CommandText = "SELECT Sum(number1) FROM Numbers"; column1sum = Convert.ToInt32(cmd.ExecuteScalar()); cmd.CommandText = "SELECT Sum(number2) FROM Numbers"; column2sum = Convert.ToInt32(cmd.ExecuteScalar()); theresultsdiv.InnerHtml += "The sum for the first column is " + column1sum.ToString(); theresultsdiv.InnerHtml += " and the sum for the second column is " + column2sum.ToString() + "."; conn.Close(); } } }
Thursday, November 20, 2008 9:47 PM -
User-1760427068 posted
Quick note, the original code used <, not < at the start of tags.
If you haven't worked with C# before, notice that almost everything ends with a semicolon. Take notes and write down which "things" don't to help you remember later.
Since I don't know your background (or that of future readers), I hope I error on the side of explaining too much. I also hope most people looking at the full example can understand a lot of it just from seeing it.
The front page (aspx) only adds three things that weren't previously there: several asp:buttons, a div element that includes runat="server" and some <br /> tags to insert blank lines.
The runat="server" must be incluced in a control or an element on the front page in order for the "things" on the code behind page to "see" the control or the element. Forgetting the runat="server" is a common error for a beginner.
There are nine lines at the top that begin with the word "using". These are namespaces. It is sometimes necessary to add a namespace at the top so that program will load something it needs in order for a particle piece of code to function. For example, "CommandType" would not function without the namespace System.Data. In this example, the first five namespaces were placed there automatically when the page was created. The remaining four namespaces were added manually.
After each manually added namespace there is a comment, beginning with two forward slashes. The comment indicates which Code or piece of code made it necessary to include the namespace. Prior to adding the namespace, a jagged red line would appear under the word. This red warning underline disappeared about two seconds after the namespace was added.
The line beginning with public partial class was put there automatically, and it is put there for every program.
If you have variables that you want to use between several subroutines you define them after this public partial class line.
In C#, the subroutine shown below: protected void Page_Load(object sender, EventArgs e){
}
is added to the page automatically. Anything in this subroutine will happen when the page loads. The only thing our program does on load is to put some text in the div. To do this, we take the id name of the div element, type .InnerHtml =, and then type the text we want within quotes. (more on this later).
Notice next that there are several protected void subroutines with names like SummationButton_Click. The program goes to one of these after the button (look for the same name in the button) is clicked. Ignore the (object sender, EventArgs e) for now, noting only that it is identical in each button click subroutine.
There are several types of variables that you will want to use (I'm assuming you already know the meanings): double, int, string. We didn't use any strings in this example.
For work with percentages, variables of the type double were used (strangely, if I did division of an integer by an integer, the result came to an integer even though that particular variable was given the type 'double'.
One quick note, when using doubles, they are set to "real" when defining the type for a field in a table.
When we come to the part where the code behind must communicate to the table in the database, we use SqlConnection (just copy the entire string for now) and SqlCommand. The example always uses a 'conn' SqlConnection and 'cmd' for the SqlCommand. You could use different words.
Glance on down and notice SqlDataReader, and still further down, a while loop. When starting out, you'll probably just want to copy all these lines, paste them in, and then make some changes.
cmd.CommandText is where you write the SQL statement. A SQL statement provides answers to several questions: What table do you want to query? What fields in this table contain the data that you need? Do you want to retrieve only records that meet a criterium or criteria (as opposed to retrieving every record)? Or course there is even more, but this should be enough initially.
The SQL statements in the examples are short and simple. The word Numbers is the name of a table. The words number1 and number2 refer to fields in the table Numbers.
Before looking at what is inside the reader loop, quickly note that reader.Read() has a corresponding reader.Close(). Too bad they didn't make it .Open() and .Close() like they did for opening and closing a connection--conn.Open() and conn.Close();
A reader will scan through the table once, selecting rows that meet the criteria. You can't turn it around and have it go backwards, or anything like that.
Within the while loop, notice that a structure like reader["field"] is used to pull text out of what stored in a field, in a record. I say text at this point because until you do something to it, the program doesn't know the type of the data (integer, string, double, datetime, etc.) To specify a type, you "convert" the text to a type. If the content in the field something is an integer:
Convert.ToInt32(reader["something"]);
Convert.ToString(reader["anotherthing"]);
Convert.ToDouble(reader["somenumber"]);
I've found that if something is going into a string, it isn't always necessary to convert to string. However, I'd recommend doing it every time to avoid the trouble of having to track down and find a problem. Conversion is necessary if text is a number and you want to use it for math.
The SQL statement is slightly different for when we want the sum of a column:
"SELECT Sum(number1) FROM Numbers"
You might guess there are other things where you do something by typing a word and then writing the field name within parentheses. Yes.
Sum is an example of a SQL aggregate function (see http://www.w3schools.com/sql/sql_functions.asp).
Now, instead of using ExecuteReader(), we use ExecuteScalar().
If the result of a SQL statement would be just one number, it is convenient to use ExecuteScalar(), add a conversion and set a variable equal to that expression.
What would happen if the SQL statement was written in a way that it DIDN'T result in a single value and you used ExecuteScalar()? It wouldn't crash. It would take the first result and give that to you, and ignore all the others.
The above covers what is present in the example.
BONUS FEATURES:
We put data into a div element using .InnerHtml (example: dividname.InnerHtml = "This is some text";)
You can do something similar with .Text to put a string into a TextBox (example: textboxidname.Text = "Some text";)
Or you can take content from a TextBox (example: string mystring = textboxidname.Text;)
Regarding Executions, you've seen ExecuteReader() and ExecuteScalar(). There are others but the next one you will want to find is ExecuteNonQuery(). This third executioner is used when you want to use SQL statements to do operations on your database such as INSERT INTO, UPDATE, DELETE, etc.
FINALLY
If it turns out that you are a VB person, a lot of the above will be the same, or at least similar. I'm happy to repeat the example in VB for you.
Regards,
-Larry
Thursday, November 20, 2008 9:56 PM -
User-318386396 posted
Buddy many many thanks for helping me with ur code thats good
but the problem that i m facing is the make calculations with in the grid rows or if we bring rows from db table then we should edit them and make calculations in the fields of 1 row.e.g in a row if we write '1' in 1st field and place '2' in 2nd field then on blur third field contain its sum i.e 3.and all this should be done for each row in a grid or table. and then we can update.
I m doing all this in c#.
once again thanks of ur good response but can u solve this problem in the way that i tell u above
Sunday, November 23, 2008 12:36 AM -
User-1760427068 posted
Please find SQL code below for a second example. This example takes a quantity value and a price and multiplies these two together for a subtotal. It then calculates a 5% tax and adds this to the subtotal to calculate the total cost.
CREATE TABLE TotalCost
(id smallint IDENTITY(1,1) PRIMARY KEY,
quantity smallint NOT NULL,
price real NOT NULL,
tax real NOT NULL,
total real)Sunday, November 23, 2008 7:24 AM -
User-1760427068 posted
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TotalCost.aspx.cs" Inherits="TotalCost" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> Quantity: <asp:TextBox ID="QuantityTextBox" runat="server"></asp:TextBox> <br /><br /> Price: <asp:TextBox ID="PriceTextBox" runat="server"></asp:TextBox> <br /><br /> (a 5% state tax will be added to your order...) <br /><br /> <asp:Button ID="SendButton" runat="server" Text="Send" onclick="SendButton_Click" /> <br /><br /> <asp:SqlDataSource ID="TotalCostSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [quantity], [price], [tax], [total] FROM [TotalCost]"></asp:SqlDataSource> <asp:GridView ID="TotalCostGridView" runat="server" AutoGenerateColumns="False" DataSourceID="TotalCostSqlDataSource"> <Columns> <asp:BoundField DataField="quantity" HeaderText="quantity" SortExpression="quantity" /> <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" /> <asp:BoundField DataField="tax" HeaderText="tax" SortExpression="tax" /> <asp:BoundField DataField="total" HeaderText="total" SortExpression="total" /> </Columns> </asp:GridView> </form> </body> </html>
Sunday, November 23, 2008 8:55 AM -
User-1760427068 posted
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; // This was added to make SqlConnection function using System.Configuration; // This was added to make ConfigurationManager function using System.Data; // This was added to make CommandType function public partial class TotalCost : System.Web.UI.Page { int quantity; double price; double tax; double subtotal; double totalcost; protected void Page_Load(object sender, EventArgs e) { } protected void SendButton_Click(object sender, EventArgs e) { quantity = Convert.ToInt32(QuantityTextBox.Text); price = Convert.ToDouble(PriceTextBox.Text); subtotal = quantity * price; tax = subtotal * 0.05; totalcost = subtotal + tax; SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); string sqlcommand = "INSERT INTO TotalCost (quantity, price, tax, total) VALUES (" + quantity + "," + price + "," + tax + "," + totalcost + ")"; SqlCommand cmd = new SqlCommand(sqlcommand, conn); cmd.CommandType = CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); TotalCostGridView.DataBind(); } }
Sunday, November 23, 2008 8:57 AM -
User-1038969477 posted
Hi shoaibrizwan ,
Try to use javascript code to implement this .
See this sample :
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable table = new DataTable(); table.Columns.Add("col"); for (int i = 0; i < 10; i++) { DataRow dr = table.NewRow(); dr["col"] = i.ToString(); table.Rows.Add(dr); } this.GridView1.DataSource = table; GridView1.DataBind(); } } int count = 0; string boxes = ""; protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { TextBox box = e.Row.FindControl("TextBox1") as TextBox; box.Attributes.Add("onblur","dowork();"); boxes += "'"+box.ClientID+"',"; count += Convert.ToInt32(box.Text); } if (e.Row.RowType == DataControlRowType.Footer) { TextBox box = e.Row.FindControl("TextBox2") as TextBox; box.Text = count.ToString(); boxes = boxes.Substring(0,boxes.Length -1); this.ClientScript.RegisterArrayDeclaration("boxes", boxes); this.ClientScript.RegisterHiddenField("foot", "" + box.ClientID + ""); } }
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound" ShowFooter="True" Width="327px"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("col") %>'></asp:TextBox> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> <script> function dowork() { var temp = 0 ; for(var i = 0 ;i < boxes.length;i++) { temp += parseInt( document.getElementById(boxes[i]).value,10) ; } document.getElementById( document.getElementById("foot").value).value = temp.toString (); } </script>
Monday, November 24, 2008 4:52 AM -
User-1760427068 posted
Ihave a grid view in which edit insert update delete each work is ok but now i have to do calculations in my grid i.e i have to calculate value from one field of grid and on that basis calculate percentages,additions,subtraction and show data on the next field e.g there are two fields percentage,total sum
now from percentage and a given value i calculate total sum and show next to percentage.this all work should also be done while editing the data in grid view.Is this all possible ?any solutions....??
Hi Shoaibrizwan:
I looked through the example provided by the previous poster and I realized, you never said that you wanted to include a database table. Was this an incorrect assumption on my part? If so, I can make an example that doesn't do anything with a table if you would like one.
I played with the new example (Thank you, Samu! :-)) and found I needed to add a namespace (I added 'using System.Data' to the top of the code behind page). I don't know if this has happened to you yet--you put in code and red squiggly lines appear under some words, in this case DataTable and DataRow. When you mouseover one of them the message is "The type or namespace name 'DataTable' could not be found (are you missing a using directive or an assembly reference?) This would be a good time for you to start a page in a notebook where you write down the name of the Namespace when the code behind contains a particular word. The first time you encounter one, the best I can recommend is to google the offending word with 'C#' and 'Example' and hope that you are lucky to quickly find a full example that shows the namespaces.
-Larry
Monday, November 24, 2008 6:18 AM -
User-318386396 posted
now i can give u a grid so that u have an exactly the idea.that is my simple grid but in this grid i edit the row boxes by using the wizard of dats source.
when u exec this grid u ll find columns like percentage and budget.
there is an over all budget field on the page(other than grid) i.e total budget=120
Now in grid on pressing the edit the row turns in to text boxes that is ok.(as u know during edit a grid)
but during edit i want following changes in edit text boxes
when we enter a percentByPhase value in grid i.e 10
then on leaving that cell(i.e on blur) calculate 10/100 of 120 and value comes in budget field
then on pressing the update button in grid will update the database values
I think now u understand.this is my source code for a simple grid
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="check.aspx.cs" Inherits="check" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Total Budget<asp:TextBox ID="TextBox1" runat="server">120</asp:TextBox><br />
<br />
<asp:SqlDataSource ID="DSforEdit" runat="server" ConnectionString="<%$ ConnectionStrings:mpr01ConnectionString %>"
SelectCommand="SELECT [Stage], [Description], [PercentByPhase], [Overall], [Budget], [ID] FROM [milestone_Dept]"
DeleteCommand="DELETE FROM [milestone_Dept] WHERE [ID] = @ID"
InsertCommand="INSERT INTO [milestone_Dept] ([Stage], [Description], [PercentByPhase], [Overall], [Budget]) VALUES (@Stage, @Description, @PercentByPhase, @Overall, @Budget)"
UpdateCommand="UPDATE [milestone_Dept] SET [Stage] = @Stage, [Description] = @Description, [PercentByPhase] = @PercentByPhase, [Overall] = @Overall, [Budget] = @Budget WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Stage" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="PercentByPhase" Type="Double" />
<asp:Parameter Name="Overall" Type="Double" />
<asp:Parameter Name="Budget" Type="Double" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Stage" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="PercentByPhase" Type="Double" />
<asp:Parameter Name="Overall" Type="Double" />
<asp:Parameter Name="Budget" Type="Double" />
</InsertParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView2" runat="server" DataSourceID="DSforEdit"
Width="588px" Height="89px" >
<Columns>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
i apreciate ur good response
Regards
shoaib
Tuesday, November 25, 2008 12:34 AM -
User-1760427068 posted
CREATE TABLE milestone_Dept (ID int IDENTITY(1,1) PRIMARY KEY, Stage nvarchar(20) NOT NULL, Description nvarchar(100) NOT NULL, PercentByPhase real NOT NULL, Overall real NOT NULL, Budget real NOT NULL)
OK, I have a page that works, and it has your front page code and the database created from the above SQL statement. If anyone else tries this, I made a change to the SqlConnection line, reverting it to a default value.
Question: I don't understand what goes in 'Overall'.
Here is my understanding of this. Assume our project is to make a movie and we have three phases:
Design, Getting experts together to decide what needs to be done, 20%
Production, Making the movie and paying stars and crew, 30%
Marketing, paying for TV ads and other media to promote it, 50%
If our budget is $200 million then Design gets $40 million, Production gets $60 million and Marketing gets $100 million.
Is overall supposed to add up as we go along? (20% at Design, 50% at Production, and 100% at Marketing)
-Larry
Tuesday, November 25, 2008 9:20 PM -
User-318386396 posted
Actually its a budget management application in which we distribute the budget in different departments and categories it is the sub page of a categories of employees salary.
consider one department 'business evelopment(BD)'
consider total budget for whole project is some value
BD is the 30% of total budget
now there are some mile stones in order to complete BD
we further break down this 30% in to these mile stones
now if u see my above grid then i hope u understand that whats going on
on that page we have total value of 30%
percent by phase means break up of 30%(i.e 70% of 30)
overall means over all % of project budget
BUdget field means total estimated value for this phase of total budget
Wednesday, November 26, 2008 12:54 AM -
User-1760427068 posted
For our next step we want to do something I haven't tried until today -- to make a Gridview that is a combination of columns that come from a table in a SQL database and also a column (or later columns) that is based on calculations.
PHASE I - making a simple example that works
Notice
([columnA]+[columnB]) AS total
in the SelectCommand in the SqlDataSource.PHASE II - adding edit and insert functionality to it (caution: I've watched controls self-destruct when doing this strictly from the front page so I'm somewhat worried--we would then try to do it from the code behind if it failed)
PHASE III - build the example with your described table (I wanted to do the first work with a simpler system to make it easier to figure out from looking at it)
Please find below first the SQL statements to build the table in your database and then the code for the front page. Nothing was done to the code behind page.
**************************************
CREATE TABLE Math (id smallint IDENTITY(1,1) PRIMARY KEY, columnA real NOT NULL, columnB real NOT NULL)
**************************************
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="VB_GridView2.aspx.vb" Inherits="VB_GridView2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [columnA], [columnB], [id], ([columnA]+[columnB]) AS total FROM [Math]" ConflictDetection="CompareAllValues" > </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource2" AutoGenerateColumns="false"> <Columns> <asp:BoundField HeaderText="A" DataField="columnA"></asp:BoundField> <asp:BoundField HeaderText="B" DataField="columnB"></asp:BoundField> <asp:BoundField HeaderText="total" DataField="total"></asp:BoundField> </Columns> </asp:GridView> </form> </body> </html>
Saturday, November 29, 2008 7:51 PM -
User-1760427068 posted
Please find below the aspx page for PHASE II (again, no code behind) that includes edit functionality.
************
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="VB_GridView2.aspx.vb" Inherits="VB_GridView2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Math] ([columnA], [columnB]) VALUES (@columnA, @columnB)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [id], [columnA], [columnB], ([columnA]+[columnB]) AS total FROM [Math]" UpdateCommand="UPDATE [Math] SET [columnA] = @columnA, [columnB] = @columnB WHERE [id] = @original_id AND [columnA] = @original_columnA AND [columnB] = @original_columnB"> <UpdateParameters> <asp:Parameter Name="columnA" Type="Single" /> <asp:Parameter Name="columnB" Type="Single" /> <asp:Parameter Name="original_id" Type="Int16" /> <asp:Parameter Name="original_columnA" Type="Single" /> <asp:Parameter Name="original_columnB" Type="Single" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="columnA" Type="Single" /> <asp:Parameter Name="columnB" Type="Single" /> </InsertParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource2" AutoGenerateColumns="False" DataKeyNames="id"> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:BoundField HeaderText="A" DataField="columnA" SortExpression="columnA"></asp:BoundField> <asp:BoundField HeaderText="B" DataField="columnB" SortExpression="columnB"></asp:BoundField> <asp:BoundField DataField="total" HeaderText="total" ReadOnly="True" SortExpression="total" /> </Columns> </asp:GridView> </form> </body> </html>
Saturday, November 29, 2008 8:03 PM -
User-1760427068 posted
I need some help with your story (we call these "story problems" where you write a paragraph of sentences to describe something that will ultimately become a math problem or in this case a computer problem).
Which of the following statements are true?
1) You have several departments
2) Each department can have several projects
3) Each project can have several phases
If several or all of these statements are true we would need several tables. One table would have a column for projects, a column for what percentage of the budget the project was given, and a column for the department name.
Another table would have a column for project and a column for phase, and a column for what percentage of the project budget the phase had been allocated.
At this point we're discussing database design, which is very important. However, I don't know if you want for me to continue since the question of how to put a column into a GridView that does a calculation has been answered:
to review,
- we added something to the select statement in the SqlDataSource that created a calculation and gave it a name so we could later refer to it by name
- we went to GridView and built a new column that was slightly different from the others, and it referred to the name.
I did see a question I haven't worked into this yet--how to make the value of a textbox be a part of the calculation:
For example, maybe the number in the textbox is 120 and a department has 10% of the overall budget and their Marketing Project is half of their budget and Phase II is 25% of the Marketing project. We would want the math to determine that (in sequence: 10% of 120 is 12, half of 12 is 6, and finally 25% of 6 is 1.5-- final answer 1.5)
Is this correct?
-Larry
Saturday, November 29, 2008 8:56 PM -
User-1760427068 posted
This uses the Math table for which the SQL statement was provided in a previous post
*****************
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS_GridView3.aspx.cs" Inherits="CS_GridView3" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:TextBox ID="TotalBudgetTextBox" runat="server"></asp:TextBox> <br /><br /> <asp:Button ID="Button" runat="server" Text="Calculate" onclick="Button_Click" /> <br /><br /><br /> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Math] ([columnA], [columnB]) VALUES (@columnA, @columnB)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [id], [columnA], [columnB], ([columnA]+[columnB]) AS total, ([columnA] * @totalbudget) AS multiplied FROM [Math]" UpdateCommand="UPDATE [Math] SET [columnA] = @columnA, [columnB] = @columnB WHERE [id] = @original_id AND [columnA] = @original_columnA AND [columnB] = @original_columnB"> <SelectParameters> <asp:ControlParameter Name="totalbudget" ControlID="TotalBudgetTextBox" Type="Double" PropertyName="Text" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="columnA" Type="Single" /> <asp:Parameter Name="columnB" Type="Single" /> <asp:Parameter Name="original_id" Type="Int16" /> <asp:Parameter Name="original_columnA" Type="Single" /> <asp:Parameter Name="original_columnB" Type="Single" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="columnA" Type="Single" /> <asp:Parameter Name="columnB" Type="Single" /> </InsertParameters> </asp:SqlDataSource> <asp:GridView ID="GridView3" runat="server" DataSourceID="SqlDataSource2" AutoGenerateColumns="False" DataKeyNames="id"> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:BoundField HeaderText="A" DataField="columnA" SortExpression="columnA"></asp:BoundField> <asp:BoundField HeaderText="B" DataField="columnB" SortExpression="columnB"></asp:BoundField> <asp:BoundField DataField="total" HeaderText="total" ReadOnly="True" SortExpression="total"></asp:BoundField> <asp:BoundField DataField="multiplied" HeaderText="total" ReadOnly="True" SortExpression="multiplied"></asp:BoundField> </Columns> </asp:GridView> </form> </body> </html>
**************aspx code above*******************aspx.cs code below***********************
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class CS_GridView3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // This if statement protects us--each time the button is clicked the page will go // through this loop and change the value back to 1--unless we prevent it with // this loop that will only be true if the page is truly loading for the first time if (!Page.IsPostBack) { TotalBudgetTextBox.Text = 1.ToString(); GridView3.DataBind(); } } protected void Button_Click(object sender, EventArgs e) { GridView3.DataBind(); } }
Saturday, November 29, 2008 9:36 PM -
User-1760427068 posted
WHAT TO LOOK FOR:
There are more lines in this than in a typical entry level example. I hope it is still "see-able", meaning you understand things by just seeing them.
The piece
([columnA] * @totalbudget) AS multiplied
in the SelectCommand does the math work and uses
@totalbudget
to refer to
<SelectParameters> <asp:ControlParameter Name="totalbudget" ControlID="TotalBudgetTextBox" Type="Double" PropertyName="Text" /> </SelectParameters>
From there, the Control Parameter "sees" the value in the textbox given the name TotalBudgetTextBox and we tell the computer that the value it takes from the textbox (i.e., the Text property of the textbox) is of the type double (I'm guessing if we didn't specify this it might assume that text from a textbox was of type string.
Action occurs at the press of a button--we have the GridView redone.
If you haven't seen a
if (!Page.IsPostBack)
loop before, we needed that because every time the button is pushed the program will go through the loop and we only want it to execute the instructions there if the program has just loaded (and no button pushed yet).
Let me know if you have any questions on this. Also, I wrote questions for you in the previous post if you would like to continue.
Alternately, you might be considering this post finished since the examples now show how to do calculations in a column in a GridView and the examples also show how a constant in a textbox can be used in the calculations performed within a GridView.
Best regards,
-Larry
Saturday, November 29, 2008 9:47 PM -
User1649851808 posted
I have the same problem,, did you find the solution?
I know it's too many years ago when you post this :)
Thursday, September 8, 2016 7:31 PM