How to perform calculation on gridview and output results to new column?

I am using a SQL Data source to populate a GridView control in .NET 3.5.  It returns 1 column.  I want to use the data in this column with a hash function and output the hash into a second column.  So, effectively, I want the original value returned from the query in column 1 and the hash in column 2.  I can get the data, but, am not sure how to implement outputting the hash into a second column.  Can anyone give some suggestions?

 

0
Will
5/4/2009 9:40:30 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

1 Replies
881 Views

Similar Articles

[PageSpeed] 21

Please find the sample code to fix your issue. I have a GridView with two columns. Column1 is populated from the DataSource and the Column2 is calculated on the fly. Dynamically updating the second column is done in the gvFiles_RowDataBound event.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
   
        <asp:Label ID="lblHeader" runat="server" Text="Grid View Data Bound"></asp:Label>
        <br />
        <asp:GridView ID="gvFiles" runat="server" DataSource="<%# DTGVSource %>"
            AutoGenerateColumns="false" onrowdatabound="gvFiles_RowDataBound">
            <Columns>
                <asp:TemplateField HeaderText="Col1">
                    <ItemTemplate>
                        <asp:Label ID="lblData" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Col1") %>' >
                        </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Hash Col1">
                    <ItemTemplate>
                        <asp:Label ID="lblHashData" runat="server" Text="" >
                        </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <br />
    </div>
    </form>
</body>
</html>

 Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Page.DataBind();
        }
    }

    public DataTable DTGVSource
    {
        get
        {
            DataSet dsFiles = new DataSet();
            dsFiles.ReadXml(Page.Server.MapPath("XMLFile.xml"));
            dsFiles.WriteXml(@"C:\test.xml");
            return dsFiles.Tables[0];
        }
    }

    protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblCol1 = (Label)e.Row.FindControl("lblData");
            if (lblCol1 != null)
            {
                string col1Value = lblCol1.Text;
                Label lblHashCol1 = (Label)e.Row.FindControl("lblHashData");
                if (lblHashCol1 != null)
                {
                    lblHashCol1.Text = col1Value + " Hash";//calculate you hash value here and assign
                }
            }
        }
    }

}

 

XML file used:

<?xml version="1.0" encoding="utf-8" ?>
<NewDataSet>
  <File>
    <Col1>1</Col1>
  </File>
  <File>
    <Col1>2</Col1>
  </File>
  <File>
    <Col1>3</Col1>
  </File>
</NewDataSet>
 
0
RemithR
5/4/2009 11:07:29 PM
Reply:

Similar Artilces:

New column to a datatable and binding datatable to GridView Control
Hi,    I am trying to add a column to a dataset and trying to bind the data to a GridView Control. But it alwasy displaying the first row. What I am doing wrong here. I need to add new Fund_Name to each row of my data table.   lstrSql = "SELECT FUND_IDENT_ID, FUND_NAME FROM FUND_IDENTITY WHERE FUND_IDENT_ID IN( '2617','2479','2752','2747') " 'Next ' daFundIdentList = New SqlDataAdapter(lstrSql, sqlConnection)Dim cmdDBCommand = New SqlCommand(lstrSql, sqlConnection) Dim drDBReader As SqlDataReader 'executing the...

Gridview control removing consecutive spaces in column output
 Hi, i am using a simple GridView to retrieve data from a SQL view, and if there are consecutive spaces in the string in a particular column, something (asp?) is removing the 2nd space, and then the output has only 1 space, which is incorrect for this string. Interestingly, if I retrieve the same column with a specific select statement in a code behind file, and then output it via either response.write, or in a text box, it does the same thing.   I have debugged while doing this and in the Autos window, the string is correct (with two consecutive spaces), then when it is ...

calculate result of 3 drop downs in gridview columns
 Hi all,I am trying to get the result of 3 drop down lists as a product.  eg. if 2, 3 and 5 were selected from the 3 dropdowns, the label value would be 2x3x5 or 30.  Below is the aspx and c# code I have so far.  At the moments the event Button1_Click does not recognise my dropdowns.  Please help.  Its all very new to me.  Someone suggested I will need to use the Findcontrol method.  I have tried but could not get it to work.   The code then: aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Defa...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

performing percentage calculation in SQL query results & checking for 0 & rounding down of calculation result
hiI got SQL query which return some numbers like this:select num1, num2 from tblnumi want to calculate % value like so:select num1, num2, total = (num1 / (num1 + num2)  * 100 ) from tblnum  The problem is that:1. SQL seem to round DOWN num1 / (num1 + num2) ....so everything becomes 0 ( I can do num1 * 100 / (num1 + num2) to get the percentage but it still I think get rounded down)2. How do I write nice SQL code to handle div by zero error when (num1 + num2) is 0? thanksS        1, SELECT (CAST (@num1 AS FLOAT)/(@num2 + @num3) *100) AS res&n...

GridView calculated columns .. best place for minimal performance hit ??
RE: GridView calculated columns .. best place?? I've got this table without about 5000 rows. I know as rule you should limit the number of rows passed to the grid. But with sorting and paging options, I'd like to send them all there. Previously, the datasource was a db view with a few columns that were derived from a db function. A real performance killer taking 3 minutes to display the grid. If I remove the function columns of course the sql comes right back fast. I was thinking maybe I perform the calculation as rows are displayed maybe in the forms prerender codebehind even...

how to open new window when click on the dynamic column in gridview control
Hi I am working with Gridview Control with c#.net.from database i am loading 10 columns dynamically on the gridview control.i have to open new widow through javascript when i click on the 8th column.how can i write on click event for the dynamic column in gridview control.your help appreciatable. Thanks in advance        shiva Do you have a hyperlink or button in the 8th column?  And should this happen on each row or the header? Rob Millswww.dotnetadvisor.com...

Binding GridView Columns with controls outside the GridView
HiI already posted this issue but couldn't get the proper resolution so making it more clear;Problem is my controls are outside the grid. Like ive text boxes, for First Name and Last Name and dropdown for country. User can fill these fields for entering a new record and also update the existing by selecting it from the grid.Like user selects a row from the grid and its contents will be displayed on the textboxes and drop downs that are out side the grid.Hope i could explain it better now.  RegardsMohsin Shahzad You could use a DetailsView or FormView control that is linked to the GridView.  This way, you are still updating external from the GridView, but using another *View control that will also link to a DataSource that allows for updating and inserting of records on a one-by-one basis.For more information, look at the QuickStart tutorials for the DetailsView and FormView controls. Christopher Reed"The oxen are slow, but the earth is patient." wolfenstein4u:I already posted this issue but couldn't get the proper resolution so making it more clear;Problem is my controls are outside the grid. Like ive text boxes, for First Name and Last Name and dropdown for country. User can fill these fields for entering a new record and also update the existing by selecting it from the grid.Like user selects a row from the grid and its contents will be displayed on the textboxes and drop downs that are out side the grid. where is your ...

How can I control the width of a column in the GridView control.
From searching I see mention of ways to do it before the controls are bound. Is there a simpler way? If not, could someone explain to me how I need to go about it?Here is the code: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"        DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display."        OnSelectedIndexChanged="GridView1_SelectedIndexChanged">   &nbs...

Is there a control that offers the same data presentation as a GridView, but allows users to copy and paste many rows/columns at once?
 Hi Is there a control that offers the same data presentation as a GridView, but allows users to copy and paste many rows/columns at once onto the grid? What I mean is some grid that 's as flexible as MS Excel grid for example.  Any suggestions will be very much appreciated.E The Repeater control is a highly customisable data presentation controlRohin.NET developerNever trust a computer you can't throw out a window. - Steve WozniakPlease remember to click on 'Mark as answer', if this post helped you......

gridview control in another gridview control
Hi ia have a questioni have a gridview control which contains button in one colum.now my question is i need another gridview to be placed in the  first gidviewso that when i click on the button the second gridview will populate the data.now my question is how to place second gridview in first gridview.or is there any approach like first grid itself acting as parent and child.please help me  Hi sirikalavalapalli:                I think nested gridview will help you. Check this link and it will show you how...

Help Req: !!! :- On Disabling Controls Present inside a Gridview control
Hi All, We have A requirement Where we have disable controls inside a grid.These controls can be textbox, DropDownlist (in TemplateField), ComandField present inside the grid.We have to call a generic method for doing the same .(since it can be done for multiple grid.) PFB the code snippet we use. Which disables all the controls inside the page.The bolded part of the code is used to loop inside a grid view.(Not Working.)Is this ideal way to deal with the requirement.Or can someone suggest be a better way.        public void DisableMe(Page p1, st...

remove a gridview column dynamically, removes controls in template columns
I have a interface with a treeview and a gridview. The gridview has two templatefields that handles insert/update/deletes. The gridview is handling editing of different tables so I create the other columns in the gridview dynamically as boundfields. The user selects the table to edit in the treeview. The problem I am having happens when the user selects a table to edit the second time. The code that executes removes all bound fields, (dynamically added when user selected the first table in the treeview), but not the two template fields, and then adds boundfields specific for the selected table. The problem (bug ?) is that this removes all controls (Imagebuttons) in the template fields. So, to reproduce, just remove a column in i gridview with template fields. This will remove all controls in all the template fields. (I haven't tried the result if removing predefined columns) If I use commandfield's instead of templete fields the code works fine. But... I don't want to do that. Greatful for every suggestion. Hi:   Please paste a demo that can reproduce your problem. ThanksSincerely,Allen ChenMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help. Thanks for the reply.  I will paste how the gridview looks in the aspx. The gridview is really in some divs, (to handle x-y scrolling) and a updatepanel and the gridview really has...

New Column in GridView which accumilative adds the totals from another column.
Hello everyone, I've tried to search for a solution on here but I've come up empty. Here is an example of my gridview   DATE     |     Amount    |01/06/08           2002/06/08           3003/06/08           1004/06/08           80 What I need now is a column next to Amount which accumilative adds the "Amount"...

to Calculated Columns, then to update another column in same table in ADO.NET
to get several Columns, then pass those Columns into  one function which will return  a result,then using the result to update another column in same table in ADO.NET, How can I do this? thanks. Hi   what ever information you given is not clear. so please give me  detail info.Ganesan  Clarity is required. Plz explain clearly wts u r requirement.Thank uBaba Thank uBabaPlease remember to click "Mark as Answer" on this post if it helped you. ...

Calculate a column in a Gridview based on data in another column of the same Girdview?
Anybody got any ideas? I'm stumped. I want a column in a gridview to take the value of another column in the same row as a parameter and run a query and then bind it. Like I said I'm stumped.   Bill I don't think you can pass the value of another column in the same row as a parameter and run a query and then bind it.  However, you could write a query with a calculated column from another field.  LynnPlease mark replies that have helped you as answers. Hi CoreslabBill, You can do it in RowDataBound event of GridView control. Here is my sample. In my samp...

New Column in GridView which accumilative adds the totals from another column. #2
Hello everyone, I've tried to search for a solution on here but I've come up empty. Here is an example of my gridview   DATE     |     Amount    |01/06/08           2002/06/08           3003/06/08           1004/06/08           80 What I need now is a column next to Amount which accumilative adds the "Amount"...

Disable button server control under GridView when one of the Column in Gridview Total is Zero
Hi web page(aspx) consist of a GridView with two columns displayed from Database. GridView has two columns 1)Employees_Department and 2)Total_Employees. In Employees_Department column employee department name is retrieved and displayed as a Hyperlink when Total_Employees column value is not Zero(This is achieved using row_databound event code shown below). Clicking or selecting particular Employees_Department row will open data for that Employees_Department in a new window. In Total_Employees column of the GridView, total number of employees in that(row) department displayed. GridView is ...

calculated column in a gridview
I have a grid view looks like below. I am trying to make Column A and B as the calculated column. Let's say. As I enter a number in the column C and click calculate button, it will automatically insert numbers into column A and B based on the fomular ( A = C *  key and B = C + key ) and gives you the options either update or cancel. How can I do this? Any examples that I can look at it?     Key A B C   Update Cancel 36 Calculate Edit 37       Calculate Edit 38       Calculate...

How to manipulate images and combe multiple database columns into one column in a GridView control
Hi Folks,I'm hoping someone can help me out with something.I am trying to put together a photo album as a learning exercise and have a GridView control with two columns linked to an Access Data Source. In the left hand column (called Image) I want to display the photo and in the right hand column (called Details) I want to provide details such as Date, Location, People and Comments, Camera Type etc. Each of these is columns is taken from the database I have set up.However, I have am having some problems:1: At the moment I have been able to get the image to display (using an image column ...

Issue with Template Columns & Bound Columns while updating the data in a GridView control
Hi, I'm facing the below problem (In general, ObjectDataSource is driving me crazy ! ) I have a simple gridview control and an ObjectDataSource is used to populate the grid. I'm trying to update a row and the corresponding tableadapter methods & stored procedure are in place. Each row has 2 checkboxes and 2 textboxes in edit mode. When the change the values in edit mode and hit update, the checkbox values changed are saved into the Database properly, whereas the textbox values are not being saved. If the textbox column is a bound column then the column is updated with <NULL> in...

Gridview edit How to subract one column from another show result in 3rd column.
If a user edits ShippingWeightGr or ShippingWeithTr I need it to subtract ShippingweithGr - ShipingWeightTr and put it in the ShipingweightNet.       How can I do this?  Here is my gridview code     <asp:GridView ID="GridView1" runat="server" AllowPaging="True"             AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Id"             DataSourceID="SqlDataSource1...

Gridview control embedded in another gridview control
I am writing an ambulance crew scheduling application on the web and I need some help completing the last part.  I have an access database that has three tables: user table, shift table (describing the shifts available), and a schedule table (that stores shift by shift_id and user by user_id).  I have a gridview control that will display the available shifts but I cannot get the embedded gridview control that will display the user that is signed up for each shift to display because I cannot figure out how to use the OnRowDataBound method.  I need a simple VB example of how to...

using javascript getting value from textbox when edit button is clicked and both controls are present in gridview control
Hi All using javascript I want to get value  from textbox when edit button is clicked and both controls that is texbox and button are present in gridview control .Alok Hi aloksinha83, Please see this post: http://forums.asp.net/t/1069245.aspx Thanks,Qin Dian TangMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them if they provide no help....

Web resources about - How to perform calculation on gridview and output results to new column? - asp.net.presentation-controls

Calculation - Wikipedia, the free encyclopedia
A calculation is a deliberate process that transforms one or more inputs into one or more results, with variable change. The term is used in ...

Facebook to adjust calculations for total check-ins displayed on place pages
Facebook says it will change how check-ins are calculated so that place pages more accurately reflect how many people visited a location. According ...

App Store - Civil Engineering Calculations
Get Civil Engineering Calculations on the App Store. See screenshots and ratings, and read customer reviews.

Canterbury Bulldogs prop David Klemmer bolts into Kangaroos calculations
Canterbury giant David Klemmer is set to be handed a Test debut as the Kangaroos look to bolster their depleted forward stocks but the Australians ...

Sydney Swans star Ben McGlynn bursts into All Australian calculations
Ben McGlynn is the latest Sydney star to burst into All Australian calculations after continuing his rich vein of form against Port Adelaide, ...

By any calculation Melbourne kid Alex Gunning was No. 1 at world maths Olympiad
When you calculate the sheer maths of the challenge confronting him last week, the odds of Alex Gunning finishing on top were almost unfathomable. ...

Tricolours show true colours to surge into calculations
Let it now be official. Sydney Roosters have a serious scalp. Having won on Monday night against Manly under trying circumstances - at Brookvale ...

Commentary: Manila's wrong calculation
Commentary: Manila's wrong calculation People's Daily Online Links. Global TimesChinadaily.com.cn Ecns.cn Show ChinaChina Human RightsChina ...

4 Recommendations (and 1 Calculation) to Improve Social Media Engagement
Marketers often have a spectrum of goals for their Facebook pages. From growing awareness to converting Fans into email subscribers, many marketers ...

Cameron's refugee calculation
The UK pledged to admit more refugees in the country, but it is not enough.

Resources last updated: 2/16/2016 4:34:30 AM