I have the code below
protected void BubbleButton_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Expand")
{
string strMonth = string.Empty;
string status = string.Empty;
string strCategory = "";
int idxCategory = 0;
if (e.CommandArgument != null)
{
string[] commandArgs = e.CommandArgument.ToString().Split(new string[] { "^" }, StringSplitOptions.None);
strCategory = commandArgs[0];
strMonth = commandArgs[1];
status = commandArgs[2];
hdnBubbleId.Value = "rptTimeLine_btn" + strMonth + status;
if (status == "B1")
{
status = "1";
}
else if (status == "B2")
{
status = "0";
}
else if (status == "B3")
{
status = "2";
}
}
DataTable dtDistinctCategoryValues = new DataTable();
Params = new Dictionary<string, object>();
Params["#status"] = Convert.ToInt32(status);
Params["#monthShortName"] = strMonth;
Params["#CategoryName"] = strCategory;
Params["#idx_Client"] = Convert.ToInt32(Session["Client_id"]);
string ProcName = "usp_getTaskDetailsByStatusCategoryAndMonth";
dtGetTaskdetails = new BusinessLogicCore().ExecuteDataTable(ProcName, Params, connection);
// to show the detailed view grid only bubble contain more than 1 task
if (dtGetTaskdetails.Rows.Count > 1)
{
/*Commented on 03/15/2016*/
DataView view = new DataView(dtGetTaskdetails);
dtDistinctCategoryValues = view.ToTable(true, "CategoryName");
RepeaterItem rptrow = ((sender as System.Web.UI.WebControls.Button).NamingContainer as RepeaterItem);
Repeater rptDetailsView = (Repeater)rptrow.FindControl("rptMarketingTimeLineDetiledView");
rptDetailsView.DataSource = dtDistinctCategoryValues;
rptDetailsView.DataBind();
ImageButton imgPlus = (ImageButton)rptrow.FindControl("imgPlus");
ImageButton imgMinus = (ImageButton)rptrow.FindControl("imgMinus");
hdnDetailsView.Value = "bubble";
hdnShowTaskDiv.Value = "0";
hdnMonthName.Value = "";
hdnIdx_task.Value = "";
hdnlnkTaskId.Value = "";
// Page.ClientScript.RegisterStartupScript(this.GetType(), "ExpandBubbleGrid", "ExpandDiv('" + imgPlus.ClientID + "', '" + imgMinus.ClientID + "');", true);
}
}
protected void rptMarketingTimeLineMonthDetiledView_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
GridView gridView = (GridView)e.Item.FindControl("GVMarketingTimeLineMonthlyDetiledView");
if (gridView != null)
{
DataRowView dataRowView = (DataRowView)e.Item.DataItem;
gridView.DataSource = GetPolicyDetailsByCategory(Convert.ToString(dataRowView["CategoryName"]));
gridView.DataBind();
}
}
}
Above give is my code behind code.
<asp:Button ID="btnDecB1" runat="server" rel="popover" data- toggle="popover" OnCommand="BubbleButton_Command" OnClientClick="return false;" CommandName="Expand" CommandArgument='<%#Eval("CategoryName")+"^Dec^B1"%>' Style="display: none;" onmouseover="dotBlink(this.id);" onmouseout="removedotBlink(this.id);" />
<div id="myPopover1" class="popover">
<div class="arrow"></div>
<div class="popover-content">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<asp:Repeater ID="rptMarketingTimeLineDetiledView" runat="server" OnItemDataBound="rptMarketingTimeLineDetiledView_ItemDataBound">
<HeaderTemplate>
<table class="tblDetiledView">
</HeaderTemplate>
<ItemTemplate>
<tr style="margin-bottom: 10px; background-color: white;">
<td style="text-align: left;" nowrap="true">
<asp:Label ID="lblCategory" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"CategoryName") %>' CssClass="fontBold" Style="color: #23356E;"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="GVMarketingTimeLineDetiledView" runat="server" AutoGenerateColumns="false" GridLines="None" Style="width: 100%;" HeaderStyle-CssClass="MarketingTimeLineDetailedGridHeaderStyle" OnRowDataBound="RowDataBound" DataKeyNames="idx_task" ToolTip="Select a row to edit task details.">
<AlternatingRowStyle BackColor="#CDE5F5" />
<Columns>
<asp:BoundField DataField="TaskName" HeaderText="Task Name" ItemStyle-Width="20%" HeaderStyle-CssClass="MarketingTimeLineHeader" ItemStyle-CssClass="MarketingTimeLineitem" />
<asp:BoundField DataField="StartDate" HeaderText="Start Date" ItemStyle-Width="12%" HeaderStyle-CssClass="MarketingTimeLineHeader" DataFormatString="{0:MM/dd/yyyy}" ItemStyle-CssClass="MarketingTimeLineitem" />
<asp:BoundField DataField="ClientContacts" HeaderText="Client Contact" ItemStyle-Width="20%" HeaderStyle-CssClass="MarketingTimeLineHeader" ItemStyle-CssClass="MarketingTimeLineitem" />
<asp:BoundField DataField="StatusName" HeaderText="Status" ItemStyle-Width="15%" HeaderStyle-CssClass="MarketingTimeLineHeader" ItemStyle-CssClass="MarketingTimeLineitem" />
</Columns>
</asp:GridView>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</div>
And above one is aspx code
And my javascript code is
$('[rel="popover"]').each(function () {
var $this = $(this);
$this.popover({
offset: 10,
trigger: 'click',
placement: 'right',
html: true,
content: $('#myPopover1').text(),
});
$('#mypopover').click(function () {
$(".popover").popover('hide');
});
});
When I click on the button the page is refreshed and if I give OnClientClick="return false;" it will on go to oncommand function. How can I get the details of repeater and grid view in popup?
Related
i'm facing problem on how to get selected checkbox(single or multiple) and post back to method for save data from modal.
The function of checkbox javascript is working, so far no idea on how to put them in ajax and post.
Ajax still can't get the data of checkbox while checkbox is clicked!
Here is my modal gridview code for ASPX:
<div class="modal-dialog">
<div class="modal-body">
<asp:UpdatePanel ID="updateGV" runat="server">
<ContentTemplate>
<asp:Label CssClass="bolder" runat="server" ></asp:Label>
<input type="text" name="AddGroup" class="form-control" id="CreateGroup" onblur="GroupCheck()" />
<br /><br />
<asp:GridView runat="server" ID="gvLIST" CssClass="table table-bordered"
AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="gvCHECKALL" runat="server" onclick="allCHKBOX(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="gvCHECK" runat="server" onclick="singleCHKBOX(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat ="server" Text='<%#Eval("ID") %>' style="display:none"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="NME"/>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<button id="btnROUPSAVE" runat="server" disabled="disabled" onclick="btnGroupSaveClick()" >
</div>
</div>
<script type="text/javascript">
function singleCHKBOX(chkBOX) {
var IsChecked = chkBOX.checked;
var Parent = document.getElementById('gvLIST');
var chkALL;
var items = Parent.getElementsByTagName('input');
var unchkALL = true;
for (i = 0; i < items.length; i++) {
if (items[i].id.indexOf('gvCHECKALL') != -1) {
chkALL = items[i];
continue;
}
if (items[i].type == "checkbox" && items[i].checked == false) {
unchkALL = false;
break;
}
}
chkALL.checked = unchkALL;
}
function allCHKBOX(spanChk) {
var IsChecked = spanChk.checked;
var cbxAll = spanChk;
var Parent = document.getElementById('gvLIST');
var items = Parent.getElementsByTagName('input');
for (i = 0; i < items.length; i++) {
if (items[i].id != cbxAll.id && items[i].type == "checkbox") {
items[i].checked = IsChecked;
}
}
}
</script>
function btnGroupSaveClick()
{
var CreateGroup = $("#CreateGroup").val().trim();
if (CreateGroup!= "" )
{
$.ajax({
type: "POST",
url: "test.aspx/CreateGroup",
data: "{'CreateGroup':'" + CreateGroup+ "', 'gvCHECK':'" + gvCHECK+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
Hy,
I facing a little problem to do something who seems easy...
In an ASP.NET page I have a repeater who present result from a research.
Until now an aspButton to do the job of redirection.
But I would like this redirection append when the user clic anywhere in my result line to replace my button.
I tried something in JavaScript and jquery but I can't get this to work...
Here is the code of my repeter :
<asp:Repeater ID="rptProfil" runat="server" onitemdatabound="rptProfil_ItemDataBound">
<ItemTemplate>
<div id="divLine" class="divProfil <%# Container.ItemIndex % 2 == 0 ? "lineLignt" : "lineDark" %>">
<asp:HiddenField ID="hdnPerson" runat="server"/>
<table class="table100">
<tr>
<td class="rptLeft">
<div id="divName" runat="server">
<asp:Label ID="profilName" runat="server" Text='No data' CssClass="lbProfilNom" />
<asp:Label ID="profilFname" runat="server" Text='No data' CssClass="lbProfilNom" />
</div>
</td>
<td class="rptCenter">
<asp:Label ID="store" runat="server" Text='No data' CssClass="lbSecondary" />
</td>
<td class="rptRight textCenter">
<asp:Button ID="btnShowDetails" runat="server" OnClick="BtnShowDetailsClick" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
In the code behind section, nothing particular :
protected void rptProfil_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Person = (SearchItem)e.Item.DataItem;
var id = (HiddenField)e.Item.FindControl("hdnPerson");
var name = (Label)e.Item.FindControl("profilName");
var fname = (Label)e.Item.FindControl("profilFname");
var line = (Label)e.Item.FindControl("line");
var city = (Label)e.Item.FindControl("city");
var zip = (Label)e.Item.FindControl("zip");
var store = (Label)e.Item.FindControl("store");
id.Value = Person.PersonId.ToString();
name.Text = Person.LastName;
fname.Text = Person.FirstName;
line.Text = Person.AddressLigne;
city.Text = Person.City;
zip.Text = Person.ZipCode;
store.Text = Person.Level3Name;
}
protected void BtnShowDetailsClick(object sender, EventArgs e)
{
var btnShowDetails = (Button)sender;
var item = (RepeaterItem)btnShowDetails.NamingContainer;
var hdnPerson = (HiddenField)item.FindControl("hdnPerson");
Response.Redirect(string.Format("ProfilDetails.aspx?id={0}", hdnPerson.Value));
}
Instead of the following code
<asp:Button ID="btnShowDetails" runat="server" OnClick="BtnShowDetailsClick" />
Try doing
<input type="button" onclick="redirect($(hdnPerson))">
and under script
<script>
var redirect=function(obj){
window.location="ProfilDetails.aspx?id="+$(obj).val();
}
</script>
Hope this helps.
I have a gridview and scenario is: once someone deletes a row, it checks if NOTIF_RECIP_SEQ_NBR is maximum or not. If yes then it deletes that row else give a popup.
So basically once someone click on delete, it gets the NOtif_recip_Id of that row and iterates through Gridview to see if NOTIF_RECIP_SEQ_NBR of any row corresponding to that NOTIF_RECIP_ID is greater or not.
Question is It possible at client side? I did it with server side but I don't think that's a good way when I have all data on client side itself.
Please help. I tried multiple ways with Javascript but no use.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function check(var a ,var b)
{
var grid = document.getElementById("GridView1");
var cellPivot;
debugger;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++)
{
//here I want code to iterate and compare value.Is it possible?
alert("You must select an answer for all columns if Pivot is yes")
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<table>
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label13" runat="server" Text="Notif_Recip Data" BackColor="Azure"></asp:Label>
<asp:GridView ID="GridView1" runat="server" DataKeyNames="NOTIF_RECIP_GUID" emptydatatext="There are no data records to display."
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor="Beige"
HeaderStyle-BackColor = "AppWorkspace"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "NOTIF_RECIP_ID">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNOTIF_RECIP_ID" runat="server"
Text='<%# Eval("NOTIF_RECIP_ID")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="v1txtNOTIF_RECIP_ID" runat="server" ControlToValidate="txtNOTIF_RECIP_ID" Text="?" ForeColor="Red" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "NOTIF_RECIP_SEQ_NBR">
<ItemTemplate>
<asp:Label ID="lblNOTIF_RECIP_SEQ_NBR" runat="server"
Text='<%# Eval("NOTIF_RECIP_SEQ_NBR")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("NOTIF_RECIP_GUID")%>'
OnClientClick = "ValidateGrid"
Text = "Delete" OnClick = <%# "javascript:check('" + Eval("NOTIF_RECIP_SEQ_NBR")" + "Eval("NOTIF_RECIP_ID") + "')" %> ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<HeaderStyle Font-Bold="True" />
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
I found the solution so pasting for anyone who in need.
<script type = "text/javascript">
function GetSelectedRow(lnk) {
debugger;
var table, tbody, i, rowLen, row, j, colLen, cell;
var result = confirm('Do you want to delete this value ?');
if (result) {
var x = document.getElementById('Label100');
table = document.getElementById("GridView1");
tbody = table.tBodies[0];
var bool = true;
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var RecipID = row.cells[0].innerText;
var Sqqno = parseInt(row.cells[1].innerText);
for (i = 1, rowLen = tbody.rows.length; i < rowLen; i++) {
row = tbody.rows[i];
var newrecipId = row.cells[0].innerText;
if (newrecipId == RecipID) {
cell = row.cells[1];
var newseq = parseInt(row.cells[1].innerText);
if (Sqqno < newseq) {
// debugger;
bool = false;
x = document.getElementById('Label100');
x.innerHTML = "ERROR-Delete RecipId with max Seqnumber";
x.style.display = "block";
return bool;
break;
}
}
else {
bool = true;
}
}
return bool;
}
else {
return false;
}
}
</script>
I have Implemented the Search on gridview for columns from this
link. I implemented as per my requirement.But it is not working for me. Please see the code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" class="hoverTable" AutoGenerateColumns="false" AllowPaging="True" BackColor="#E5E5E5" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" ForeColor="Black" GridLines="Vertical" ShowFooter="true" PageSize="5" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating" OnRowDeleting="grdCSRPageData_RowDeleting" OnRowCommand="grdCSRPageData_RowCommand" OnDataBound="grdCSRPageData_DataBound">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:CheckBoxField DataField="Active" HeaderText="Active" ItemStyle-Width="15" />
<asp:TemplateField HeaderText="Edit/Delete" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />
<span onclick="return confirm('Are you sure want to delete?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete"></asp:LinkButton>
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<HeaderTemplate>
<asp:Button ID="btnInsertRecord" runat="server" Text="Add" CommandName="Insert" />
</HeaderTemplate>
<HeaderStyle Width="15%"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the JS script
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="js/quicksearch.js"></script>
<script type="text/javascript">
$(function () {
$('.form-control').each(function (i) {
$(this).quicksearch("[id*=grdCSRPageData] tr:not(:has(th))", {
'testQuery': function (query, txt, row) {
return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
}
});
});
});
</script>
Also see the code behind for your ref:-
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdCSRPageData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdCSRPageData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdCSRPageData.HeaderRow.Parent.Controls.AddAt(1, row);
}
Changes for the grid
protected void grdUser_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdUser.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdUser.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
if (grdUser.Columns[i].HeaderText != "Action" && grdUser.Columns[i].HeaderText != "" && grdUser.Columns[1].HeaderText != "Select") // && grdUser.Columns[i].HeaderText != "" && grdUser.Columns[i].HeaderText != null && grdUser.Columns[i].HeaderText != "Select")
{
cell.Controls.Add(txtSearch);
}
row.Controls.Add(cell);
}
grdUser.HeaderRow.Parent.Controls.AddAt(1, row);
}
When I add the HeaderText != Select. It stops working for the first column, but it works for the other column
There are a lot of elements with form-control class. So can you change your C# code to be:
protected void grdCSRPageData_DataBound(object sender, EventArgs e)
{
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
for (int i = 0; i < grdCSRPageData.Columns.Count; i++)
{
TableHeaderCell cell = new TableHeaderCell();
TextBox txtSearch = new TextBox();
txtSearch.Attributes["placeholder"] = grdCSRPageData.Columns[i].HeaderText;
txtSearch.CssClass = "form-control HaydaBre";
cell.Controls.Add(txtSearch);
row.Controls.Add(cell);
}
grdCSRPageData.HeaderRow.Parent.Controls.AddAt(1, row);
}
and your JS code to be:
<script type="text/javascript">
$(function () {
$('.HaydaBre').each(function (i) {
$(this).quicksearch("[id*=grdCSRPageData] tr:not(:has(th))", {
'testQuery': function (query, txt, row) {
return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1;
}
});
});
});
</script>
I am doing project on asp.net. Right now I have got problem with insert data from gridview to sql server. In my gridview I have add a template as a textbox in order to input value. My problem is about insert value from textbox of gridview to sql server. My code as below:
<%# Page Title="" Language="C#" MasterPageFile="~/coca.Master" AutoEventWireup="true" CodeBehind="Orders.aspx.cs" Inherits="AssignmentWeb.Orders" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="center">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=txtQty]").val("0");
});
$("[id*=txtQty]").live("change", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$("[id*=txtQty]").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());
});
</script>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="AverageProduct" HeaderText="AverageProduct" SortExpression="AverageProduct" ItemStyle-CssClass="price"/>
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField HeaderText="QtyOrder">
<ItemTemplate>
<asp:Textbox ID="txtQty" 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>
Grand Total:
<asp:Label ID="lblGrandTotal" runat="server" Text="0"></asp:Label>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:InventoryRouting %>" SelectCommand="SELECT [ProductName], [AverageProduct], [Description], [ProductID] FROM [Product]"></asp:SqlDataSource>
<br />
<asp:Button ID="btnOrder" runat="server" Text="Order!" Width="100px" OnClick="btnOrder_Click"/>
<br />
<br />
</div>
</asp:Content>
<script runat="server">
public void btnOrder_Click(object sender, EventArgs e)
{
int c = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("Data Source=LIDA-PC; Initial Catalog=InventoryRouting; Integrated Security=True");
//cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID, #ProductName, #QtyOrder, #Total)";
cmd.CommandText = "insert into orders values('" + Session["Username"].ToString() + "',#ProductID , #ProductName, #QtyOrder, #Total)";
cmd.Connection .Open();
//cmd.Parameters.AddWithValue("'" + Session["Username"].ToString() + "'", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#ProductID", GridView1.Rows[i].Cells[0].Text);
cmd.Parameters.AddWithValue("#ProductName", GridView1.Rows[i].Cells[1].Text);
cmd.Parameters.AddWithValue("#QtyOrder", GridView1.Rows[i].Cells[4].Text);
cmd.Parameters.AddWithValue("#Total", GridView1.Rows[i].Cells[5].Text);
//InsertCommand = new SqlCommand("INSERT INTO [orders] ([client], [product], [amount], [price]) VALUES ('" + Session["Username"].ToString() + "', #ProductName, #AverageProduct, #QtyOrder, #Total)");
cmd.ExecuteNonQuery();
cmd.Connection.Close();
c = c + 1;
}
}
</script>
You need to convert grid view row cell control to the appropriate control explicitly.
access like this ((Textbox)(GridView1.Rows[i].Cells[4].Controls[0]).Text for your #QtyOrder
and ((Label)(GridView1.Rows[i].Cells[5].Controls[0]).Text for #Total.
OR
(GridView1.Rows[i].FindControl("txtQty") as TextBox).Text
Thanks.