Getting sum of an unbound data column in asp.net Gridview - sql

I am trying to get the sum of an unbound data column. Basically I have a gridview with dropdown list and an Amount column. I select quantity from that list and the price is multiplied with the quantity and the amount is shown in the "Amount" column. The Price is fetched from the database and itemID also. Now I want to sum up all the values in the "Amount" column. As I run this code, every row is updated successfully with the quantity and price multiplication but the total amount logic is adding the item_price + any value in the "amount" column. I only want the data to be added in the "Amount" column. I have a label in the bottom of the grid view where I am trying to get the total result value. HELP!!
The aspx file is like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
OnRowDataBound="GridView1_RowDataBound" ShowFooter="true">
<footerstyle backcolor="LightCyan"
forecolor="MediumBlue"/>
<Columns>
<asp:BoundField DataField="item_ID" HeaderText="ID" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="ddlQuantity" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlQuantity_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="purchase_price">
<ItemTemplate>
<asp:Label ID="lblPrice" Text='<%#Eval("purchase_price") %>' runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblAmount" Text="0.00" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Here is the code behind:
protected void ddlQuantity_SelectedIndexChanged(object sender, EventArgs e)
{
int quantity;
GridViewRow gvr = ((DropDownList)sender).NamingContainer as GridViewRow;
var ddlQuantity = gvr.FindControl("ddlQuantity") as DropDownList;
var lblAmount = gvr.FindControl("lblAmount") as Label;
var lblPrice = gvr.FindControl("lblPrice") as Label;
int.TryParse(ddlQuantity.SelectedValue, out quantity);
//Label1.Text = quantity.ToString();
int pr = int.Parse(lblPrice.Text);
int qt = int.Parse(ddlQuantity.SelectedValue);
//Label2.Text += (pr*qt).ToString();
lblAmount.Text = (pr * qt).ToString();
int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
sum += int.Parse(lblAmount.Text);
}
Label2.Text = sum.ToString();
}

You were pretty close. In your sum loop, you are only adding the same amount each time. Within that loop, you need to look up each lblAmount (for that row) and sum each one.
Try this code for your loop:
int sum = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
gvr = GridView1.Rows[i] as GridViewRow;
var lblRowAmount = gvr.FindControl("lblAmount") as Label;
sum += int.Parse(lblRowAmount.Text);
}
Label2.Text = sum.ToString();

Related

How to replace IDs of users with their fullNames in the current scenario?

I have two databases with the following schema:
tbl_users(userID, fullName, emailID, password)
userID is the Primary Key
tbl_savings(savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, ownerID, dataEnteredByID)
savingsID is the Primary Key.
ownerID is a Foreign Key on userID of tbl_users with a one-to-many relationship.
ownerID specifies the ID of the owner of the saving. Similarly, dataEnteredByID specifies the ID of the person who entered the data.
I have a GridView with the following specification:
<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" DataKeyNames="savingsID" OnRowCommand="GridViewSavingsTracker_RowCommand" AllowPaging="true" OnSelectedIndexChanged="GridViewSavingsTracker_SelectedIndexChanged" OnPageIndexChanging="GridViewSavingsTracker_PageIndexChanging" PageSize="10">
<Columns>
<asp:CommandField ShowSelectButton="true" />
<asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
<asp:BoundField DataField="amount" HeaderText="Principal Amount" />
<asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
<asp:BoundField DataField="interestType" HeaderText="Interest Type" />
<asp:BoundField DataField="interestCalculationMethod" HeaderText="Interest Calculation Method" />
<asp:BoundField DataField="insertedDate" HeaderText="Date" />
<asp:BoundField DataField="ownerID" HeaderText="Owner" />
<asp:BoundField DataField="dataEnteredByID" HeaderText="Data Entered By" />
</Columns>
</asp:GridView>
What I want to do: Instead of printing the ownerID and dataEnteredByID, I want to print the fullNames of the corresponding IDs. How can I do that?
What I already have: I have the following server side code for GridView. I have a method ShowGridView() that populates the data into the GridView from the database(s).
protected void ShowGridView()
{
string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string showGridViewQuery = "(SELECT s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName FROM tbl_savings s LEFT JOIN tbl_users u ON s.ownerID = u.usersID) UNION (select s.creditorName, s.amount, s.interestRate, s.interestType, s.interestCalculationMethod, s.insertedDate, u.fullName from tbl_savings s LEFT JOIN tbl_users u ON s.dataEnteredByID = u.usersID)";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
}
You can create a separate code-behind method that gets the full name and call it from the gridview.
Create an ItemTemplate for the field. The Text property calls the method. Replace UserID with your field's name.
<ItemTemplate>
<asp:Label ID="lblUserNameItem" runat="server"
Text='<%# GetUserNameByID(Eval("UserID").ToString()) %>'></asp:Label>
</ItemTemplate>
Code behind:
protected string GetUserNameByID(string userID)
{
// your data-code...
... uname = GetUserByID(int.Parse(userID));
return uname;
}
Do the same with the other id, with the same method or another.

Display ContactName from Guid in Gridview using SQLDataSource / Asp.Net

I have set the following code up to display player1 v player2 in a Gridview. However, It currently displays tblFixtures.player1 v tblFixtures.player2 which are UniqueIdentifiers, I need it to display their corresponding contact names instead. tblaccounts has columns accountID(uniqueidentifier) and contactName(varchar) but not sure how to join this in such a way that I can display them in the Gridview below.
<asp:SqlDataSource ID="DSFixtures" runat="server" ConnectionString="
<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT
tblFixtures.player1, tblFixtures.player2, tblFixtures.compID,
tblFixtures.round
FROM tblFixtures INNER JOIN tblCompetitions ON tblFixtures.compID =
tblCompetitions.compID WHERE tblFixtures.compID = #Event_ID and round =
#Round ">
<SelectParameters>
<asp:QueryStringParameter QueryStringField="compID" Name="Event_ID" />
<asp:QueryStringParameter QueryStringField="round" Name="Round" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Gridview ID="gdvFixtures" visible="false" width="100%"
runat="server" AllowPaging="True" AutoGenerateColumns="False"
CssClass="mGrid" DataKeyNames="compID" DataSourceID="DSFixtures"
PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="player1" HeaderText="player1" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
V
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="player2" HeaderText="player2" />
</Columns>
</asp:GridView>
You can do a nested select
SELECT tblFixtures.player1, (SELECT name FROM tblaccounts WHERE
(accountID = tblFixtures.player1)) AS player1_name, ...
Or create another 2 joins, one for each player. You can do that by renaming the tables with AS so you can join the same table multiple times.
INNER JOIN tblaccounts AS acc1 ON acc1.accountID = tblFixtures.player1 INNER JOIN
tblaccounts AS acc2 ON acc1.accountID = tblFixtures.player2
UPDATE
Your entire query should look like this. And player1_name and player2_name become the column names you can use in a GridView.
SELECT
tblFixtures.player1,
(SELECT name FROM tblaccounts WHERE (accountID = tblFixtures.player1)) AS player1_name,
tblFixtures.player2,
(SELECT name FROM tblaccounts WHERE (accountID = tblFixtures.player2)) AS player2_name,
tblFixtures.compID,
tblFixtures.round
FROM tblFixtures INNER JOIN tblCompetitions ON tblFixtures.compID =
tblCompetitions.compID WHERE tblFixtures.compID = #Event_ID and round =
#Round

Use a selected item from a dropdownlist in a SELECT query

I have following code which is a drop down list of flight locations:
Where to:<br />
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1"
DataTextField="Destination"
DataValueField="Destination" Width="222px">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Destination] FROM [tblFlight]">
</asp:SqlDataSource>
I want to be able to use the selected value from the drop down list above (one of them is Corfu) as the WHERE condition of a query that will only select the flights going to Corfu.
Any suggestions?
basically:
string dest = yourDropDown.SelectedItem;
SELECT [Destination] FROM [tblFlight] WHERE [Destination] = " + dest;

Conditional Display of Custom Button on DevExpress ASPxGridView in VB.NET

I have an ASPxGridView control that needs a button that is visible on a conditional basis. I have searched and read several articles but have not found a fix for my particular situation. The button is called btnAllocatePlan and it should only be displayed if the value in a column called PayPlanFlg is true. Below is the markup for the grid and two things I tried in the codebehind, which is where I'd rather do this. Actually neither of these events even fired. Any help is greatly appreciated!
<dx:ASPxGridView ID="grdPayments" runat="server" CssClass="tblLined" SettingsPager-PageSize="50"
AutoGenerateColumns="False" KeyFieldName="PaymentKey" Width="100%">
<SettingsBehavior AllowFocusedRow="True" ProcessFocusedRowChangedOnServer="True" />
<Columns>
<dx:GridViewDataTextColumn Caption="CaseKey" FieldName="CaseKey" Visible="False" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Name" FieldName="Name" VisibleIndex="1" Width="10%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Association" FieldName="AssociationName" VisibleIndex="2" Width="15%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Address" FieldName="Address1" VisibleIndex="3" Width="15%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Paid" FieldName="Amount" VisibleIndex="4" Width="5%">
<PropertiesTextEdit DisplayFormatString="c"></PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Payment Date" FieldName="TransactionTime" VisibleIndex="5" Width="12%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Payment Type" FieldName="PaymentType" VisibleIndex="6" Width="3%">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Owed" FieldName="Balance" VisibleIndex="7" Width="5%">
<PropertiesTextEdit DisplayFormatString="c">
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Amount Available" FieldName="AmountAvailable" VisibleIndex="8" Width="6%">
<PropertiesTextEdit DisplayFormatString="c">
</PropertiesTextEdit>
</dx:GridViewDataTextColumn>
<dx:GridViewDataHyperLinkColumn Name="AllocationLink" VisibleIndex="9" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocate" runat="server" Text="Allocate" OnClick="btnAllocate_Click" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
<dx:GridViewDataHyperLinkColumn Name="PlanLink" VisibleIndex="10" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocatePlan" runat="server" Text="Pay Plan" OnClick="btnAllocatePlan_Click" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
<dx:GridViewDataTextColumn Caption="PayPlanFlg" FieldName="PayPlanFlg" Visible="false" VisibleIndex="11">
</dx:GridViewDataTextColumn>
</Columns>
</dx:ASPxGridView>
Codebehind attempts:
Protected Sub grdPayments_CustomButtonInitialize(sender As Object, e As ASPxGridViewCustomButtonEventArgs)
If e.Button.ID = "btnAllocatePlan" Then
If grdPayments.GetRowValues(e.VisibleIndex, 11, "PayPlanFlg") = 1 Then
e.Button.Visibility = GridViewCustomButtonVisibility.Invisible
End If
End If
End Sub
Protected Sub ASPxGridView1_HtmlDataCellPrepared(sender As Object, e As ASPxGridViewTableDataCellEventArgs)
If e.DataColumn.FieldName = "ID" Then
Dim textBox As ASPxButton = TryCast(ASPxGridView1.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "btn"), ASPxButton)
If Convert.ToString(e.GetValue("ItemName")).Equals("B") Then
textBox.Text = Convert.ToString(e.CellValue)
textBox.Visible = True
Else
textBox.Visible = False
End If
End If
End Sub
The best approach is to handle the Button's Init/Load event. This
recommended technique is described in the The general technique of
using the Init/Load event handler KB article.
Check below example code for hiding a particular button in a row..
aspx
<dx:GridViewDataHyperLinkColumn Name="AllocationLink" VisibleIndex="9" Caption=" " UnboundType="String" Width="5%">
<DataItemTemplate>
<!--<%#"Allocate"%>-->
<dx:ASPxButton ID="btnAllocate" runat="server" Text="Allocate" OnInit="btnAllocate_Init" />
</DataItemTemplate>
</dx:GridViewDataHyperLinkColumn>
.cs
protected void btnAllocate_Init(object sender, EventArgs e)
{
DevExpress.Web.ASPxButton btn = (DevExpress.Web.ASPxButton)sender;
GridViewDataItemTemplateContainer container = btn.NamingContainer as GridViewDataItemTemplateContainer;
// You can remove the if statement, and try to insert a new record. You'll catch an exception, because the DataBinder returns null reference
if (container != null && !container.Grid.IsNewRowEditing)
btn.Visible = !(bool)DataBinder.Eval(container.DataItem, "PayPlanFlg");
}
Reference:
ASPxGridView - Hide the control in the DataItemTemplate conditionally

How to change a Radgrid column value after binding?

I have a Radgrid and I bind it with SqlAdapter. My problem is that I want to change just one column's value. Is that possible?
My column name is IsShadow and it binds true or false. I cannot change it. If value is false or true, I change column text appearence, not database update.
Code I've tried
foreach (Telerik.Web.UI.GridDataItem dataItem in gridShadow.MasterTableView.Items)
{
bool flag = Convert.ToBoolean(dataItem.GetDataKeyValue("IsShadow"));
GridEditableItem editedItem = dataItem as GridEditableItem;
if (!flag)
{
TableCell tableCell = editedItem["IsShadow"] = ???
}
}
Thank you.
Please try with the below code snippet and let me know if any concern.
// Normal Mode
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
item["IsShadow"].Text = "Your new text";
}
// Edit Mode
if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
{
GridEditableItem editItem = (GridEditableItem)e.Item;
(editItem["IsShadow"].Controls[0] as TextBox).Text = "Your new text";
}
You probably need a GridTemplateColumn
In the ItemTemplate you will check the value of IsShadow and display some text, but in EditItemTemplate you would probably need to just have a checkbox for true/false.
<telerik:GridTemplateColumn HeaderText="Is Shadow" UniqueName="TemplateColumn">
<EditItemTemplate>
<asp:CheckBox id="editChkBox" runat="server"
Checked='<%# Bind("IsShadow") %>'>
</asp:CheckBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Lable id="lblIsShadow" runat="server"
Text='<%# Convert.ToBoolean(Eval("IsShadow")) == true ? "it is shadow" : "Not shadow" %>'>
</asp:CheckBox>
</ItemTemplate>
</telerik:GridTemplateColumn>