Column sum of multiple columns of dynamic gridview using Javascript - javascript

I have a Dynamic asp Gridview with all columns as template feild TextBox. The columns of the Gridview are also dynamic and column count may vary everytime.
Please find code below
public void FillPoDetails()
{
DataTable dt = new DataTable();
dt = pmdata.createdatatable(int.Parse(Session["OurStyleid"].ToString()), int.Parse(Session["PoPackid"].ToString()));
GenerateTable(dt.Columns.Count, dt.Rows.Count,dt);
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
TemplateField bfield = new TemplateField();
//Initalize the DataField value.
bfield.HeaderTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Header, col.ColumnName);
//Initialize the HeaderText field value.
bfield.ItemTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label();
//Allocates the new label object.
lbl.Text = _columnName;
lbl.CssClass = "Headerclass";
//Assigns the name of the column in the lable.
container.Controls.Add(lbl);
//Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox();
//Allocates the new text box object.
tb1.DataBinding += new EventHandler(tb1_DataBinding);
//Attaches the data binding event.
tb1.Columns =6;
//Creates a column with size 4.
// tb1.Width = System.Web.UI.WebControls.Unit.Percentage(100);
tb1.Width = 100;
tb1.Wrap = true;
tb1.ID = "txt_" + _columnName;
if(_columnName== "ColorTotal")
{
tb1.CssClass = "ColorTotal";
}
else if (_columnName == "Color")
{
tb1.CssClass = "Color";
}
else
{
tb1.CssClass = "txtCalQty";
tb1.Attributes.Add("onkeypress", "return isNumberKey(event,this)");
tb1.Attributes.Add("onkeyup", "sumofQty(this)");
}
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
}
}
And inorder to get the row total I had added a Javascript function on keydown event and its working clearly
//calculate the sum of qty on keypress
function sumofQty(objText) {
var cell = objText.parentNode;
var row = cell.parentNode;
var sum = 0;
var textboxs = row.getElementsByClassName("txtCalQty");
for (var i = 0; i < textboxs.length; i++)
{
sum += parseFloat(textboxs[i].value);
}
var textboxtotalqtys = row.getElementsByClassName("ColorTotal");
textboxtotalqtys[0].value = sum.toString();
}
And the result is Like below
can anyone please help me in finding out the sum of each columns(all same cssclass).and display it in the Sizetotal row because I am not able to loop through columns

I would give every textbox a row id and a column id through html5 data attributes. and in javascript (jQuery) filter the textboxes through column id.
example:
..
var sum = 0;
$( "input[data-column-id='" + selectedColumnId + "']" ).each(function( index )
{
sum += parseFloat($( this ).val() );
});
..
By the way, use jQuery. its amazing.

Not sure about your requirement but this may help you, After binding data to grid, once again loop through the column list
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
int rowIndex=2;
GrdDynamic.FooterRow.Cells[1].Text = "Total";
GrdDynamic.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
foreach (DataColumn col in dt.Columns)
{
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>(col.Caption));
GrdDynamic.FooterRow.Cells[rowIndex++].Text = total.ToString("N2");
}

There is a very simple way.
Add Footer and Label to each Column, Then do calculations from database side best is use LINQ and Group by, find footer Label Controls for each column and Bind values to those Footer's Label Control, in this way your UI will have less load.
See here for code:
.ASPX Page in Grid:
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Literal ID="ltrlTotal" Text='<%#Eval("Total") %>' runat="server"> </asp:Literal> // For Sub Total
</ItemTemplate>
<FooterTemplate>
<strong><asp:Literal ID="ltrlGrandTotal" runat="server"> // This is Grand Total
</asp:Literal></strong>
</FooterTemplate>
</asp:TemplateField>
C# Code:
var searchResult = soService.SearchResult(companyId);
var grandTotal = searchResult.Select(so => so.Total).Sum();
searchResult.All(aa => aa.GrandTotal == grandTotal);
gridSo.DataSource = searchResult;
gridSo.DataBind();
if (searchResult.Count > 0)
{
Literal ltrlGrandTotal = gridSo.FooterRow.FindControl("ltrlGrandTotal") as Literal;
if (ltrlGrandTotal != null)
ltrlGrandTotal.Text = string.Format("Grand Total : $ {0}", grandTotal);
}

Related

How to create a drop down menu with values from spreadsheet?

I'm trying to create a drop down menu and the values inside are in a specific column of a spreadsheet.
I tried making cells with foo but i don't know how to call them to my html file. Is this efficient? Or can you show me another way to call them to my html file.
Tried this code but no idea on how to return this to html.
function email_dropdown(divname)
{
var open_sheet = SpreadsheetApp.openByUrl(')getSheetByName');
SpreadsheetApp.setActiveSpreadsheet(open_sheet);
var active_sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('*********');
active_sheet.activate();
var dropdown = "<select id = 'email_dropdown'> Email";
var row_val = active_sheet.getRange("**").getValues();
var row_length = row_val.length;
var row_data = active_sheet.getRange("**");
for (var row = 2; row <= row_length; row++)
{
dropdown = dropdown + row_data.getCell(**).getValue();
}
dropdown = dropdown + "</select>"
Logger.log(dropdown);
}
Cool, You have gotten most of this solved :) Now you need to do something like the following since you have the values in the array
function yourTestfunction() {
var exampleValues = ['one', 'two', 'three'];
// after your values have been stored in the array
var sheetValuesEl = document.querySelector("#js_sheetValues");
// populate select with values
for(var i = 0; i < exampleValues.length; i++) {
// Create the option
var optionValue = document.createElement("option");
// Set the option text
optionValue.textContent = exampleValues[i];
// Add the option to the select drop down
sheetValuesEl.appendChild(optionValue);
}
}
yourTestfunction()
<select id="js_sheetValues"></select>

Get selected value from externally created dropdownlist

I'm creating a dynamic menu that fetches dishes from a database and displays them to the user so he can add them to his order. Whenever I retrieve a row from the database I send it to my menuItems class so the columns can be read and the display format is created and inserted into a cell:
foreach (DataRow dr in drc){
//extract the dish data from the row into a cell
TableCell c1 = menuItem.makeItemCell(dr);
//display it
tr.Controls.Add(c1);
table1.Controls.Add(tr);
}
c1 will be a cell that has the dish information along with a quantity dropdownlist and an "add to order" button:
public static TableCell makeItemCell(DataRow dr)
{
TableCell tc = new TableCell();
Image img = new Image();
img.ImageUrl = (string)dr["img"];
tc.Controls.Add(img);
//rest of information adding is omitted for brevity
String myLiteral = "<p>" + "Name: " + (string)dr["NameofDish"] + "</br>";
tc.Controls.Add(new LiteralControl(myLiteral));
//add quantity label and dropdownlist populated with possible quantity values
Label lb = new Label();
lb.Text = "Quantity: ";
DropDownList ddl = new DropDownList();
for (int i = 0; i < 13; i++)
{
String t = i.ToString();
ddl.Items.Add(new ListItem(t, t));
}
//create the add to order button
Button btn = new Button();
btn.Text = "Add to order";
tc.Controls.Add(lb);
tc.Controls.Add(ddl);
tc.Controls.Add(btn);
return tc;
}
My problem is with handling the button click event. All my tries to bind it with an event handler (on the menuItems class or the codebehind itself) have failed. I could only manage to update the postbackURL of the button when it's created in the cell like this
btn.PostBackUrl = "./menu.aspx?dish=" + (string)dr["ID"] + "&quantity=" + ddl.SelectedValue;
But the .selectedvalue value is rendered when the cell is created hence is always 0
My question is this: how can I handle the button click event in a way that I can get hold of the dishID and the selected value.
((((I would prefer an event handling solution rather than querystrings if possible))))
Thank you!
EDIT:
My whole problem is that the cell and its components are created in the external class and sent back to my code. How do I access the dropdownlist variable from my codebehind if I don't have the element id or anything

Get edit item value in RadGrid client-side

i'm looking for somone that can help me on this problem:
i've a Telerik RadGrid in edit-mode, after pressing radgrid's update button i do some checks into a javascript file; i want to check the value in some cells that are in edit mode but i don't know how to see the value.
I try to explain better with an example: i have some columns editable and some read-only, for the read-only columns i can view the value but for the editable columns i view all the html of the cell and i don't know how to get only the value, here is the code
function calculate(dgRDO) {
var grid = $find(dgRDO).get_masterTableView();
var righe = grid.get_editItems();
for (var i = 0; i < righe.length; i++) {
var row = righe[i];
//i can view this value, CODART column is ReadOnly
var codart = grid.getCellByColumnUniqueName(row, "CODART").innerHTML;
//i cannot view only the value but i view the entire html of the cell, PREZZO column is editable
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").innerHTML;
}
Thanks for any suggestion
RESPONSE FROM TELERIK (IT WORKS)
In order to easily access RadGrid cells client-side you could use the ClientDataKeyNames property. It should contain the DataField names of the columns that will be accessed on the client. Illustration on extracting key values client-side is available in this article.
A sample function for accessing a column that is added to the ClientDataKeyNames collection would look similar to this:
function command(sender, eventArgs) {
var grid = $find("<%= RadGrid1.ClientID %>");
var masterTableView = grid.get_masterTableView();
var editItem = masterTableView.get_editItems()[0];
var cellValue = editItem.getDataKeyValue("Quantity");
}
Try this
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").val();

passing dynamically created ASP.NET controls to Javascript

I'm dynamically generating a textbox and a dropdownlist in my ASP.NET web app table row, I want to change value of textbox based on dropdownlist selectedindex using javascript, but I don't know how to pass these dynamically created controls to my Javascript function.
TextBox t = new TextBox();
tc.Controls.Add(t);
tr.Cells.Add(tc);
tc = new TableCell();
DropDownList ddl = new DropDownList();
ddl.Attributes.Add("onChange", "return OnFoodChange(this," + t + ");");
tc.Controls.Add(ddl);
I pass 'this' instead of my combobox, and it works fine, but textbox is not detected in my following javascript function:
function OnFoodChange(myCmb,myTxt) {
try{
var q = document.getElementById('<%= HFFoodPrice.ClientID %>').value.toString();
var q2 = q.split(';');
alert(myCmb.selectedIndex.toString());
alert(document.getElementById(myTxt.value));
for (var j = 0; j < q2.length; j++) {
if (q2[j] != '') {
var q3 = q2[j].split(',');
{
}
}
}
}
catch(err)
{
alert(err.message);
}
}
what is the correct way of passing dynamically created controls to a javascript function? should I set controls ID in my codebehind?
In C#:
ddl.Attributes.Add("onChange", "return OnFoodChange(this," + t.ClientID + ");");
in Javascript, try this:
alert(document.getElementById(myTxt).value);

Accessing the MasterTableView Edit Form in Radgrid to get reference to textbox

There are two things I would like help with please. I need help accessing the currently edited existing row in the Radgrid, as as well as the index of the Edit form when trying to add a new record to the table/
function OnClientSelectedIndexChanged(sender, eventArgs) {
var item = eventArgs.get_item();
// alert(item.get_value());
grid = $find("<%= rgSecurity.ClientID %>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems();
// alert("about to get to grid");
alert(selectedRows.length);
if (selectedRows.length > 1) {
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
alert(row);
inputField = MasterTable.getCellByColumnUniqueName(row, "Item")
alert(inputField);
if (inputField) {
inputFieldValue = inputField.value
break;
}
}
}
else
{
// alert(inputField);
}
window.radopen('<%=PopLink %>?sel=' + item.get_value() + "&avail=" + inputFieldValue, "UserRoleDialog");
return false;
}
The currently edited grid row can be retrieved on the server using the EditItems[0] collection of the master table or through the e.Item argument inside the EditCommand server event handler. The index of the edited row can be fetched from the ItemIndex property of the item referenced as explained in the first sentence.

Categories