I have a gridview with products details , and a quantity textbox which I added-it's not connected to any DB.
I want it to display for each row the cost (price*quantity) and the total cost for all rows (in label bellow).
I have a few problems with it.
1. It enters a 0 in the quantity textbox, so I need to update the quantity to 1 all the time, and then it calculates.
I know also maybe this can be done better in C# in the rowdataboundevent, suggestions would be appreciated.
please help me undarstand what's wrong.
Here is the code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=lblquantity]").val("0");
});
$("[id*=lblquantity]").live("change", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$("[id*=lblquantity]").live("keyup", function () {
if (!jQuery.trim($(this).val()) == '') {
if (!isNaN(parseFloat($(this).val()))) {
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
}
} else {
$(this).val('');
}
var grandTotal = 0;
$("[id*=lblTotal]").each(function () {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
$("[id*=hfGrandTotal]").val(grandTotal.toString())
});
</script>
and here is the code of the gridview in ASP.net.
<asp:HiddenField ID="hfGrandTotal" runat="server" />
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
EnableViewState="False" onrowdatabound="GridView2_RowDataBound">
<Columns>
<asp:BoundField DataField="Price" HeaderText="Price" ItemStyle-CssClass="price" >
<ItemStyle CssClass="price"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="ProductID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ProductID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Summary">
<ItemTemplate>
<asp:Label ID="lblSum" runat="server" Text='<%# Eval("Summary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="picPath">
<ItemTemplate>
<asp:Label ID="lblPic" runat="server" Text='<%# Eval("picPath") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "quantity">
<ItemTemplate>
<asp:TextBox ID="lblquantity" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
thanx
Make these changes
Step1. Make the price a asp:TemplateField and add a class to lblTotal like this. Also should the Quantity be a textbox in your markup as you have written?
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" CssClass="rowprice"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" CssClass="rowqty" Text="1">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" CssClass="rowtotal"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Step2. Download this numeric plugin and write this on DOMReady
$(document).ready(function() {
$(".rowqty").numeric({
decimal: false,
negative: false
});
});
This is to make the quantity textbox accept only positive integers.
Step3.
protected void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var priceLabel = e.Row.FindControl("lblPrice") as Label;
var quantityTextBox = e.Row.FindControl("txtQuantity") as TextBox;
var totalLabel = e.Row.FindControl("lblPrice") as Label;
var onKeyUpScript = String.Format(
"javascript:CalculateRowTotal('#{0}', '#{1}', '#{2}');",
quantityTextBox.ClientID,
priceLabel.ClientID,
totalLabel.ClientID);
quantityTextBox.Attributes.Add("onkeyup", onKeyUpScript);
}
}
Step3. Add an asp:HiddenField and an asp:Label with ClientIDMode="Static"
<asp:HiddenField ID="hfGrandTotal" runat="server"></asp:HiddenField>
Grand Total: <asp:Label ID="lblGrandTotal" runat="server"></asp:Label>
Step4. Add the javascript function on the page
function CalculateRowTotal(qty_id, price_id, total_id) {
var row_quantity = $(qty_id);
var row_price = $(price_id);
var row_total = $(total_id);
var qty = parseInt($.trim($(this).val()), 10);
if (isNaN(qty) || qty === 0) {
qty = 1;
row_quantity.val("1");
}
var totalAmount = parseFloat(row_price.html()) * qty;
row_total.html(totalAmount);
var grandTotal = 0;
$(".rowtotal").each(function() {
grandTotal += parseFloat($(this).html());
});
$("#hfGrandTotal").val(grandTotal);
$("#lblGrandTotal").html(grandTotal);
}
Hope this helps.
I wouldn't do this in JS since this is client side load + slower.
Fill as you said in your RowDataBound. Yours would be in the GridView2_RowDataBound.
Just find the control and cast it to the right control and fill the text.
((Label)e.Row.FindControl("lblTotal")).Text = (price * quantity);
You probably have the price and quantity stored in you dataItem.
I think you also have to convert it to a string since .Text requires a string.
You could use
(price * quantity).ToString()
or
Convert.ToString(price * quantity);
Related
I want to Fill gridview column value into given control
something like Project Title value fill inside project Title text box Problem ID fill inside Selected Problem Dropdown and so on... on button click even
i have taken as control name
Project title as txtProjectTitle,
selectProblem Id as ddlSelectProblem,
Project_Start_Date as txtProjectStartDate,
Project_Target_Date as TextBox1,
gridview as GrdTemp,
Procedd button as Button2_Click
ASPX CODE:
[![<asp:GridView ID="GrdTemp" runat="server" Style="width: 100%; text-align: center" class="table table-striped table-bordered" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="S.No." HeaderStyle-Width="5%">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("ID") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Title">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Title") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Problem ID">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Problem") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Start Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Start_Date") %>' ID="lblID</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Target Date">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Bind("Project_Target_Date") %>' ID="lblID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns> </asp:GridView>][2]][2]
C# code:
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow row = (sender as Label).NamingContainer as GridViewRow;
TextBox txtProject = row.FindControl("txtProjectTitle") as TextBox;
txtProject.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Title"]);
DropDownList ddlProblem = row.FindControl("ddlSelectProblem") as DropDownList;
ddlSelectProblem.SelectedItem.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Problem"]);
txtProjectStartDate.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Start_Date"]);
TextBox1.Text = Convert.ToString((row.Parent.Parent as GridView).DataKeys[row.RowIndex]["Project_Target_Date"]);
}
I have been searching on here and other sites for three days for a solution. I need to select one or more rows (using checkbox) and delete selected row(s) from a gridview who's datasource is a session datatable as you will see. Not interested in SQLConnections or LINQ Entities. As a result I am not sure if I need to use e.commandarguments, or how to go about it, but I have tried them with no luck.
Error is visible and clearly commented on CART.ASPX.CS page inside the following method
if (chkRemCart != null && chkRemCart.Checked)
Any assistance would be greatly appreciated and if you require any further coding or explanations to help with a solution, just ask.
Thank you in advance.
CART.ASPX
<asp:GridView ID="gvCart" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" CellPadding="4"
HeaderStyle-CssClass="header" EmptyDataText="You have successfully cleared your Shopping Cart"
OnRowDataBound="gvCart_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Movie Selector">
<ItemTemplate>
<asp:CheckBox ID="chkRemCart" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie ID">
<ItemTemplate>
<asp:Label ID="lblMovieID" runat="server" Text='<%# Eval("MovieId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:Label ID="lblDuration" runat="server" Text='<%# Eval("Duration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Genre">
<ItemTemplate>
<asp:Label ID="lblGenre" runat="server" Text='<%# Eval("Genre") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Label ID="lblRating" runat="server" Text='<%# Eval("Rating") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price","{0:n}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnRem" runat="server" OnClick="RemCart" Text="Remove Selection" CssClass="button" Title="Remove Movies From Cart" />
CART.ASPX.CS
Page_Load calling RefreshPages() method. gvCart displaying all columns and rows of items in Datasource/Session/Datatable
public void RefreshPages()
{
if (Session["SelectedMovies"] != null)
{
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
protected void RemCart(object sender, EventArgs e)
{
// Check session exists
if (Session["selectedMovies"] != null)
{
// Opening / Retreiving DataTable.
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
foreach (GridViewRow row in gvCart.Rows)
{
CheckBox chkRemCart = row.Cells[0].FindControl("chkRemCart") as CheckBox;
if (chkRemCart != null && chkRemCart.Checked)
{
// Error appearing on line below. Scroll right to read.
int MovieId = Convert.ToInt32(gvCart.DataKeys[row.RowIndex].Value); // Error here. //Additional information: Index was out of range. Must be non - negative and less than the size of the collection.
MovieTable.Rows.RemoveAt(row.RowIndex);
//Saving session
Session["selectedMovies"] = MovieTable;
// Updating gvCart
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
}
}
Assign DataKeyNames="PrimaryKey" in gridview like below and check
<asp:GridView ID="gvCart" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" DataKeyNames="MovieId" CellPadding="4"
HeaderStyle-CssClass="header" EmptyDataText="You have successfully cleared your Shopping Cart"
OnRowDataBound="gvCart_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="Movie Selector">
<ItemTemplate>
<asp:CheckBox ID="chkRemCart" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Movie ID">
<ItemTemplate>
<asp:Label ID="lblMovieID" runat="server" Text='<%# Eval("MovieId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:Label ID="lblDuration" runat="server" Text='<%# Eval("Duration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Genre">
<ItemTemplate>
<asp:Label ID="lblGenre" runat="server" Text='<%# Eval("Genre") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Label ID="lblRating" runat="server" Text='<%# Eval("Rating") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Eval("Price","{0:n}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code behind:
public void RefreshPages()
{
if (Session["SelectedMovies"] != null)
{
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
protected void RemCart(object sender, EventArgs e)
{
// Check session exists
if (Session["selectedMovies"] != null)
{
// Opening / Retreiving DataTable.
DataTable MovieTable = (DataTable)Session["SelectedMovies"];
foreach (GridViewRow row in gvCart.Rows)
{
CheckBox chkRemCart = row.Cells[0].FindControl("chkRemCart") as CheckBox;
if (chkRemCart != null && chkRemCart.Checked)
{
// Error appearing on line below. Scroll right to read.
int MovieId = Convert.ToInt32(gvCart.DataKeys[row.RowIndex].Value); // Error here. //Additional information: Index was out of range. Must be non - negative and less than the size of the collection.
DataRow[] drs = dt.Select("MovieId = '" + MovieId + "'"); // replace with your criteria as appropriate
if (drs.Length > 0)
{
MovieTable.Rows.Remove(drs[0]);
}
}
}
//Saving session
Session["selectedMovies"] = MovieTable;
// Updating gvCart
gvCart.DataSource = MovieTable;
gvCart.DataBind();
}
}
Currently the code behind label control is giving me a null value when i submit the form. How can i add the value to a local variable?
Please advise.
JAVASCRIPT
$(document).ready(function () {
$(".chk").change(function () {
var total = 0;
var chks = $(".chk input:checked");
if (chks.length > 0) {
for (var i = 0; i < chks.length; i++) {
total += parseFloat($("#" + chks[i].id.replace("courseID", "lblcoursePrice")).html());
$("#<%=courseListView.ClientID %> [id*=hfTotal]").val("");
}
}
$("#<%=courseListView.ClientID %> [id*=lblTotal]").text(total.toFixed(2));
$("#<%=courseListView.ClientID %> [id*=hfTotal]").val($(this).val());
});
});
.NET PAGE
<asp:GridView ID="courseListView" AutoGenerateColumns="false" runat="server" ShowFooter="true">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="courseID" class="chk" runat="server" />
<asp:Label ID="courseTitle" Text='<%# Eval("name") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="Label2" Text="Total" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblcoursePrice" Text='<%# Eval("price") %>' runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" Text="" runat="server"></asp:Label>
<asp:HiddenField ID="hfTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
Label courseAmount = (Label)FindControl("lblTotal");
if (courseAmount != null)
{
course = courseAmount.Text; //courseButtonList.SelectedValue;
}
As I cannot see where you are trying to find this Label control. I'll give you options.
First : In Page Load or some other function
Label courseAmount = (Label)courseListView.Rows[0].Cells[0].FindControl("lblTotal");
Second : In courseListView_RowDataBound you can call like:
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl= (Label)e.Row.FindControl("lblTotal");
}
Third :
protected void courseListView_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow valu = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int RowIndex = valu.RowIndex;
Label value = (Label)courseListView.Rows[RowIndex].FindControl("lblTotal");
string course = value.Text;
}
I have a GridView, which is populated using a linq query on button click.
I have to populate the header text dynamically, fetching from the database. The first time I click the button, the header text is not binding. But, if I click on the button a second time, the header texts are bound.
Markup:
<asp:GridView ID="grdresult" runat="server" AutoGenerateColumns="false"
OnRowDataBound="grdresult_RowDataBound">
<Columns>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol1" runat="server" Text=' <%#Eval("Col1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol2" runat="server" Text='<%#Eval("Col2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Col3") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol4" runat="server" Text=' <%#Eval("Col4") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol5" runat="server" Text='<%#Eval("Col5") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol6" runat="server" Text=' <%#Eval("Col6") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol7" runat="server" Text=' <%#Eval("Col7") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="10%">
<ItemTemplate>
<asp:Label ID="lblCol8" runat="server" Text=' <%#Eval("Col8") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Records Found
</EmptyDataTemplate>
</asp:GridView>
Codebehind:
protected void btnreport_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void BindGrid()
{
var results = "LINQ select query from database";
}).Distinct().ToList();
for (int i = 0; i < grdresult.Columns.Count; i++)
{
grdresult.Columns[i].Visible = true;
}
grdresult.DataSource = results;
grdresult.DataBind();
}
protected void grdresult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
var getColumnHeader = "LINQ query to get header text";
if (getColumnHeader != null)
{
grdresult.Columns[5].HeaderText = getColumnHeader.HCol3;
grdresult.Columns[6].HeaderText = getColumnHeader.HCol4;
grdresult.Columns[7].HeaderText = getColumnHeader.HCol5;
grdresult.Columns[8].HeaderText = getColumnHeader.HCol6;
grdresult.Columns[9].HeaderText = getColumnHeader.HCol7;
grdresult.Columns[10].HeaderText = getColumnHeader.HCol8;
grdresult.Columns[11].HeaderText = getColumnHeader.HCol9;
grdresult.Columns[12].HeaderText = getColumnHeader.HCol10;
}
}
//based on some condition i have set visibility of gridview columns
int TotalColumnCount = (int)ViewState["colcount"];
for (int i = grdresult.Columns.Count - 1; i > TotalColumnCount + 4; i--)
{
grdresult.Columns[i].Visible = false;
}
}
Instead of using the below line for binding header text
grdresult.Columns[5].HeaderText = getColumnHeader.HCol3;
i used below line which solved the issue.
e.Row.Cells[5].Text = getColumnHeader.HCol3;
This error can also occur if you are dumping an integer value into varchar() but the size of varchar is not enough. For example I was getting this error as I was cast sum() to varchar(10), and hence the error.
I changed varchar(10) to varchar(20) and the error got resolved.
In Gridview control set ClientIDMode = "Static"
So I have a new requirement that is tricky to me and I'm unable to figure out so far. I am using a gridview to insert, and update data. One of the requirements that I have is when a user manually adds a new record, if the same "deal number" exists then display a pop up. This pop up should show the record that already exists. They should be able to click 1 of 3 buttons which are "use", "discard", or "Ok". The "use" button will basically close the pop up and clear the textboxes the user was entering in. The "discard" button must delete the record that exists so the user can insert the new record using that same deal number. The reason for this is because the deal number is the most unique number for the "deals" that occur. With the way we are exporting from an old application to a new one, duplicates are downloaded, sometimes some with more information than the first time it was exported. This is why I must add a requirement for the user to choose which record for them to keep. I hope this makes sense to you all. I have dried a few things, but this is what I currently have and I'm stuck on.
The Jquery Script:
<script type="text/javascript">
$(document).ready(function () {
function showpopup() {
$("#popup").dialog("open");
}
$("#popup").dialog({
modal: true,
width: 450,
autoOpen: false,
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
$("#popup").each(function () {
var popup = $(this);
popup.parent().appendTo($("form:first"));
});
});
</script>
And now the division the script calls which has another gridview to display the existing record..
<div class="popUpStyle" title="Duplicate Deal Found!" id="popup" style="display:none">
<asp:GridView ID="gvDealTracking" runat="server" Width="200px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Stock #">
<ItemTemplate>
<asp:Label ID="lblDupStockNumber" runat="server" Text='<%# Bind("StockNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deal #">
<ItemTemplate>
<asp:Label ID="lblDupDealNumber" runat="server" Text='<%# Bind("FIMAST") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DealDate">
<ItemTemplate>
<asp:Label ID="lblDupDealDate" runat="server" Text='<%# Bind("DealDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buyer">
<ItemTemplate>
<asp:Label ID="lblDupBuyer" runat="server" Text='<%# Bind("Buyer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrossProfit">
<ItemTemplate>
<asp:Label ID="lblDupGrossProfit" runat="server" Text='<%# Bind("GrossProfit") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AmtFinanced">
<ItemTemplate>
<asp:Label ID="lblDupAmtFinanced" runat="server" Text='<%# Bind("AmtFinanced") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BankName">
<ItemTemplate>
<asp:Label ID="lblDupBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUse" Text="Use" runat="server"></asp:Button>
<asp:Button ID="btnDiscard" Text="Discard" runat="server" OnClick="btnDiscard_Click" style="display:none"></asp:Button>
<asp:Label ID="lblMessagePop" runat="server"></asp:Label>
<br />
</div>
And now the code behind that I use to try to delete the existing record..
protected void btnDiscard_Click(object sender, EventArgs e)
{
try
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
string dealnumber = ((Label)gvr.FindControl("lblDupDealNumber")).Text.Trim();
conn.Open();
SqlCommand cmdDeleteDup = new SqlCommand("DELETE * FROM Vehicle WHERE FIMAST = #FIMAST", conn);
cmdDeleteDup.Parameters.AddWithValue("#FIMAST", dealnumber);
cmdDeleteDup.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
lblMessagePop.Text = ex.ToString();
}
}
The button click isn't not firing and I do now know how to make it work. I tried a few different things but same results. I'm using a reader that checks to see if the record does exists and I show this pop up if it does have rows. It displays perfectly, just my buttons don't do anything. If this isn't the proper way to go about this, please let me know. Any guidance is greatly appreciated!
This is how I'm calling the popup in c#. This has reader that checks to see if the rows exist, and if so, it displays the existing record in the popup. I use a data adapter to do this. Then I use Page.ClientScript... to open the popup and display the results.
SqlDataReader rdr = null;
SqlCommand cmdCheckExisting = new SqlCommand("SELECT StockNumber, DealDate, Buyer FROM Vehicle WHERE FIMAST = '" + DealNumber + "';", conn);
rdr = cmdCheckExisting.ExecuteReader();
if (rdr.HasRows)
{
rdr.Close();
DataTable dt = new DataTable();
SqlDataAdapter cmdReturnExisting = new SqlDataAdapter("SELECT StockNumber, FIMAST, DealDate, Buyer, GrossProfit, AmtFinanced, BankName FROM Vehicle WHERE FIMAST = '" + DealNumber + "';", conn);
cmdReturnExisting.Fill(dt);
gvDealTracking.DataSource = dt;
gvDealTracking.DataBind();
conn.Close();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "showpopup();", true);
}
EDIT: Try removing "style='display:none'" from your div and add "autoOpen: false" into the dialog. Then the only thing your "showpopup()" function needs to do is call "$("#popup").dialog('open');"
$(document).ready(function() {
$("#popup").dialog({
modal: true,
width: 450,
autoOpen: false,
open: function(type,data) {
$(this).parent().appendTo("form");
}
});
$("#popup").each(function() {
var popup = $(this);
popup.parent().appendTo($("form:first"));
});
function showpopup() {
$("#popup").dialog("open");
}
});
I found a solution. I simply changed the buttons to LinkButtons. For some reason, everything works perfectly if asp linkbutton is placed outside or inside the gridview. Here is the popup with the gridview.
<script type="text/javascript">
function showpopup() {
$("#popup").dialog({
modal: true,
width: 590,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
};
</script>
<div class="popUpStyle" title="Duplicate Deal Found!" id="popup" style="display:none">
<asp:GridView ID="gvDealTracking" runat="server" Width="200px" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Stock #" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="lblDupStockNumber" runat="server" Text='<%# Bind("StockNumber") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dealership" SortExpression="Dealership">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Dealership") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Dealership") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Deal #" HeaderStyle-Wrap="false">
<ItemTemplate>
<asp:Label ID="lblDupDealNumber" runat="server" Text='<%# Bind("FIMAST") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="DealDate">
<ItemTemplate>
<asp:Label ID="lblDupDealDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "DealDate","{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buyer">
<ItemTemplate>
<asp:Label ID="lblDupBuyer" runat="server" Text='<%# Bind("Buyer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="GrossProfit">
<ItemTemplate>
<asp:Label ID="lblDupGrossProfit" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "GrossProfit","{0:n2}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AmtFinanced">
<ItemTemplate>
<asp:Label ID="lblDupAmtFinanced" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "AmtFinanced","{0:C}") %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="BankName">
<ItemTemplate>
<asp:Label ID="lblDupBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUse" runat="server" CausesValidation="false" OnClick="btnUse_Click" UseSubmitBehavior="false" Text="Use"></asp:Button>
<asp:Button ID="lbDelete" runat="server" UseSubmitBehavior="false" CausesValidation="False" OnClick="lbDelete_Click" Text="Delete"></asp:Button>
<asp:Label ID="lblMessagePop" runat="server"></asp:Label>
<br />
</div>
EDIT: Thanks to Chad, he pointed out that asp buttons default to use the submit behavior. Setting the UseSubmitBehavior option to false within the button solves the issue. You are now able to use asp buttons within the popup to call your c# methods.