I am having trouble with an error on a site I am working on that I've inherited, upon grabbing the source from the repository and building, then clearing out a few reference errors, I am still getting over 1000 instances of this error:
The name 'pnlDetails' does not exist in the current context (replace 'panelDetails' with any of my control names).
what this would seem to indicate is that the controls referenced server side are not declared on the page, or don't have runat=server in them, but in fact they do. it could also be a problem of the inherits attribute not matching, but it does. I have searched stackoverflow and seen this question before, though after trying some of the solutions mentioned, they did not help. I do not have any designer files for my pages. Below are some snippets of code from the aspx and aspx.cs pages. (some information redacted to protect client privacy)
My question is, why can't i reference my controls on the server side? 'paneldetails', 'rpAddresses' etc.?
default.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/org.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="directory_Default" %>
<%# Register Assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=xxxx"
Namespace="System.Web.UI.WebControls" TagPrefix="asp" %>
<%# Register TagPrefix="nu" Namespace="Leap.NuCaptcha" Assembly="leapmarketing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" Runat="Server">
<title>xxxx</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphBreadCrumb" Runat="Server">
<div id="breadCrumbFrame">Home > xxx</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphBody" Runat="Server">
<h3 class="sectionTitle"> xxx </h3>
<!--//////////// Begin Searchbox Panel ////////////-->
<asp:Panel ID="pnlSearchbox" Visible="true" runat="server" DefaultButton="lnkSearch">
<div class="info">
xxx xxx.
</div>
<h3 style="padding-bottom: 10px;">xxx:</h3>
<p>xxx xxx.</p>
<br />
<br />
<div class="addressLine">
<asp:Label ID="lblFirstName" CssClass="addressLabel" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="txtFirstName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblLastName" CssClass="addressLabel" runat="server" Text="Last Name"></asp:Label>
<asp:TextBox ID="txtLastName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblCity" CssClass="addressLabel" runat="server" Text="City"></asp:Label>
<asp:TextBox ID="txtCity" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblDistrict" CssClass="addressLabel" runat="server" Text="District"></asp:Label>
<asp:DropDownList ID="ddlDistrict" CssClass="addressDropDown" runat="server" DataSourceID="dsDistricts"
DataTextField="Name" DataValueField="DistrictID"
AppendDataBoundItems="True">
<asp:ListItem Value="">All Districts</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<asp:Label ID="lblSpecialty" CssClass="addressLabel" runat="server" Text="Specialty"></asp:Label>
<asp:DropDownList ID="ddlSpecialty" CssClass="addressDropDown" runat="server"
DataSourceID="dsSpecialties" DataTextField="xxx_certification"
DataValueField="QualificationID" AppendDataBoundItems="True">
<asp:ListItem Value="">All xxx</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<div class="addressLabel"> </div>
<asp:LinkButton ID="lnkSearch" CssClass="navButton" runat="server"
onclick="lnkSearch_Click">Search</asp:LinkButton>
</div>
</asp:Panel>
<asp:LinqDataSource ID="dsDistricts" runat="server"
ContextTypeName="org.Xrm.XrmDataContext" Select="new (DistrictID, Name)"
TableName="Districts">
</asp:LinqDataSource>
<asp:LinqDataSource ID="dsSpecialties" runat="server"
ContextTypeName="org.Xrm.XrmDataContext"
Select="new (QualificationID, xxx_certification)" TableName="Qualifications"
Where="EducationTypeID == #EducationTypeID">
<whereparameters>
<asp:Parameter DefaultValue="000" Name="EducationTypeID"
DbType="Guid" />
</whereparameters>
</asp:LinqDataSource>
<!--//////////// Begin Search Results Panel ////////////-->
<asp:Panel ID="pnlResults" Visible="false" runat="server">
<div id="ResultsTop" style="margin-bottom: 15px;">
<div id="ResultsLeft" style="float: left; padding-top: 5px;">
<h2>Search Results - <span class="BlackResults">
<asp:Label ID="lblCount" runat="server" Text=""></asp:Label></span></h2>
</div>
</div>
<br />
<br />
<br />
<asp:LinkButton ID="lnkNewSearch" CssClass="navButtonLarge" runat="server" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager2" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<br />
<asp:ListView ID="lvResults" runat="server" DataSourceID="dsSearchResults">
<itemtemplate>
<tr style="">
<td class="DirectoryItems">
<asp:LinkButton ID="lnkDetails" CommandArgument='<%# Eval("ID") %>' OnCommand="lnkDetails_Click" runat="server"><%# Eval("xxx") %></asp:LinkButton>
</td>
<td class="DirectoryItems">
<asp:Label ID="LocationLabel" runat="server" Text='<%# Eval("Location") %>' />
</td>
<td class="DirectoryItems">
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("Status") %>' />
</td>
</tr>
</itemtemplate>
<emptydatatemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.</td>
</tr>
</table>
</emptydatatemplate>
<layouttemplate>
<table runat="server" width="100%">
<tr runat="server">
<td runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="0" style="border-collapse: collapse;" width="99%">
<tr runat="server" style="border-bottom:1px solid #828283; margin-top:5px; margin-bottom:5px; padding-top:5px; padding-bottom:5px;">
<td runat="server" width="40%">
<p class="DirectoryResultsHeader">xxx</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Location</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Status</p></td>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
</td>
</tr>
</table>
</layouttemplate>
</asp:ListView>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<asp:SqlDataSource ID="dsSearchResults" runat="server" OnSelected="dsSearchResults_Selected"
ConnectionString="<%$ ConnectionStrings:MSCRM %>" CancelSelectOnNullParameter="false"
SelectCommand="
SELECT * from sometable
">
<selectparameters>
<asp:ControlParameter ControlID="txtFirstName" DbType="String" Name="FirstName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtLastName" DbType="String" Name="LastName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtCity" DbType="String" Name="City" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="ddlDistrict" DbType="Guid" Name="District" ConvertEmptyStringToNull="true" />
<asp:ControlParameter ControlID="ddlSpecialty" DbType="Guid" Name="Specialty" ConvertEmptyStringToNull="true" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Details Panel ////////////-->
<asp:Panel ID="pnlDetails" Visible="false" runat="server">
<h3>xxx Information</h3>
<br />
<asp:Repeater ID="rpDetails" runat="server" DataSourceID="dsDetails">
<itemtemplate>
<table border="0">
<tr>
<td width="125"><b>Given Name:</b></td>
<td><%# Eval("FirstName") %></td>
</tr>
<tr>
<td width="125"><b>Surname:</b></td>
<td><%# Eval("LastName") %></td>
</tr>
<tr>
<td width="125"><b>Gender:</b></td>
<td><%#Eval("Gender") %></td>
</tr>
<tr>
<td width="125"><b>Status:</b></td>
<td><%# Eval("Status") %></td>
</tr>
<asp:Panel ID="pnlSpecialty" runat="server" Visible='<%# Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" ? true : false %>'>
<tr>
<td width="125"><b>xxx:</b></td>
<td>
<asp:Repeater ID="xxx" runat="server" DataSourceID="xxx">
<ItemTemplate>
<%# Eval("xxx") %><br />
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</asp:Panel>
<tr>
<td width="125"><b>xxx:</b></td>
<td><%# Eval("xxx") %></td>
</tr>
</table>
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:Repeater ID="rpAddresses" runat="server" DataSourceID="dsAddresses" OnItemDataBound="rpAddresses_DataBound">
<headertemplate>
<h3>xxx</h3><br />
</headertemplate>
<itemtemplate>
<table border="0">
<tr>
<td valign="top" width="125"><b><asp:Label ID="lblAddressType" runat="server" Text='<%# Eval("Type") %>' /></b></td>
<td valign="top">
<asp:Label ID="lblAddressStreet1" runat="server" Text='<%# Eval("Street1") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street1")) ? false : true %>' />
<asp:Label ID="lblAddressStreet2" runat="server" Text='<%# Eval("Street2") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street2")) ? false : true %>' />
<asp:Label ID="lblAddressStreet3" runat="server" Text='<%# Eval("Street3") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street3")) ? false : true %>' />
<asp:Label ID="lblAddressCity" runat="server" Text='<%# Eval("City") %>' />, <asp:Label ID="lblAddressProvince" runat="server" Text='<%# Eval("Province") %>' /> <asp:Label ID="lblAddressPostalCode" runat="server" Text='<%# Eval("PostalCode") %>' /><br />
<asp:Label ID="lblAddressCountry" runat="server" Text='<%# Eval("Country") + "<br />" %>' Visible='<%# (Eval("Country", "{0}") == "Canada") ? false : true %>' />
<table border="0">
<asp:Label ID="lblAddressPhone" runat="server" Text='<%# "<tr><td width=50>Phone:</td><td>" + Eval("Phone") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Phone")) ? false : true %>' />
<asp:Label ID="lblAddressFax" runat="server" Text='<%# "<tr><td width=50>Fax:</td><td>" + Eval("Fax") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Fax")) ? false : true %>' />
<asp:PlaceHolder ID="cphEmailAddress" runat="server" Visible='<%# Convert.IsDBNull(Eval("Email")) ? false : true %>'><tr><td width="50">Email:</td><td><asp:LinkButton ID="lnkEmailValidate" runat="server" Text='<%# Eval("ShortEmail") %>' OnClick="ShowReCAPTCHA" /></td></tr></asp:PlaceHolder>
<asp:PlaceHolder ID="cphEmail" runat="server" Visible="false"><tr><td width="50">Email:</td><td><asp:HyperLink ID="lnkEmail" runat="server" NavigateUrl='<%# Eval("Email", "mailto:{0}") %>' Text='<%# Eval("Email") %>' /></td></tr></asp:PlaceHolder>
</table>
<asp:PlaceHolder ID="cphCaptcha" runat="server" Visible="false">
<br />
<div class="info">To view the full email address, please type the moving characters in the box below.</div>
<nu:NuCaptchaControl ID="nucaptcha" runat="server" ClientKey="LEAP|0|4|TYPE|9|CLIENTKEY|CID|4|9942|KID|4|9884|SKEY|32|bDdiOWgwdjhtNy1MdTRENG43Q1BZdyws" />
</asp:PlaceHolder>
</td>
</tr>
</table>
<br />
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:LinkButton ID="lnkDetailsBack" CssClass="navButtonLarge" runat="server" OnClick="lnkDetailsBack_Click">Back to Search Results</asp:LinkButton>
<asp:LinkButton ID="lnkDetailsNewSearch" runat="server" CssClass="navButtonLarge" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<asp:SqlDataSource ID="dsDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsSpecialty" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsAddresses" runat="server"
ConnectionString="<%$ ConnectionStrings:xxx %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Data Sources ////////////-->
</asp:Content>
default.aspx.cs
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class directory_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack && pnlDetails.Visible == true && rpAddresses.Items.Count > 0 && ((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible == true)
{
Page.Validate();
if (Page.IsValid)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmailAddress")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmail")).Visible = true;
}
}
}
protected void rpAddresses_DataBound(object sender, EventArgs e)
{
}
protected void lnkSearch_Click(object sender, EventArgs e)
{
//lvResults.DataBind();
DataPager1.SetPageProperties(0, DataPager1.PageSize, true);
ShowResults();
}
protected void ShowResults()
{
pnlSearchbox.Visible = false;
pnlResults.Visible = true;
pnlDetails.Visible = false;
}
protected void lnkNewSearch_Click(object sender, EventArgs e)
{
pnlSearchbox.Visible = true;
pnlResults.Visible = false;
pnlDetails.Visible = false;
}
protected void lnkDetails_Click(object sender, CommandEventArgs e)
{
dsDetails.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsSpecialty.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsAddresses.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
rpAddresses.DataBind();
if (rpAddresses.Items.Count == 0)
{
rpAddresses.Visible = false;
}
else
{
rpAddresses.Visible = true;
}
pnlSearchbox.Visible = false;
pnlResults.Visible = false;
pnlDetails.Visible = true;
}
protected void lnkDetailsBack_Click(object sender, EventArgs e)
{
ShowResults();
}
protected void dsSearchResults_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
lblCount.Text = String.Format("{0} Dentists found", e.AffectedRows);
}
protected void ShowReCAPTCHA(object sender, EventArgs e)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = true;
}
}
Thanks for the answers people, I did try some of these things.
Every control which you wish to access in aspx.cs should have runat="server"
they do
Build your solution after adding the above tag
If you wish to access the control defined inside the item template of repeater you
can do so only inside repeater events for by putting a loop reading
all items of repeater
they are
Right click on the page where you are getting the error and click on
convert to web application... That will solve your error.
no such option in my IDE, besides I think it would be the whole project, not a page that I convert.
Check to see if this is a web application project or a website
project. A website project would use the CodeFile attribute of the
#Page directive, but a web application project wouldn't. If it's
trying to compile as a web application project, you would receive
these errors because a web application project expects a designer file
in addition to the .aspx and .aspx.cs files. The designer contains all
the control definitions which in turn which allows you to reference
them properly in codebehind (web application uses CodeBehind and not
CodeFile attribute as well).
apparently then my project is a website, not a web application, as it includes the codefile attribute. also, I don't have designer files, so this makes sense.
Turns out I am trying to edit a solution developed in VS2008, using VS2013, and a lot has changed since then. While the issue was not resolved here, the fix was to create a new VS2013 solution and import the files, it's all working as intended now, thank you.
exclude or delete any other pages that reference the same code-behind file, for example an older page that you copied and pasted.
You may want to check the build action of the c# files in the property window in visual studio and make sure its set to Compile
Check to see if this is a web application project or a website project. A website project would use the CodeFile attribute of the #Page directive, but a web application project wouldn't. If it's trying to compile as a web application project, you would receive these errors because a web application project expects a designer file in addition to the .aspx and .aspx.cs files. The designer contains all the control definitions which in turn which allows you to reference them properly in codebehind (web application uses CodeBehind and not CodeFile attribute as well).
Right click on the page where you are getting the error and click on convert to web application... That will solve your error.
Couple of things to be checked here:
1. Every control which you wish to access in aspx.cs should have runat="server"
2. Build your solution after adding the above tag
3. If you wish to access the control defined inside the item template of repeater you can do so only inside repeater events for by putting a loop reading all items of repeater
I had this error but had just made a silly mistake. I wanted to retain the original code while I made some big changes so I copied and pasted one of the .cs files. Well, both files had the same class name. The two identical namespaces (understandably) confused the compiler. Removing the "backup" fixed it. I could have just changed the namespace, too.
Just sharing in case someone is as bone-headed as I.
Related
I have a product catalog page. When you click on the "Add Product" button, page with a cart shows up. This page has a table with an ItemTemplate inside it. Is there any way to get the value from the textBox located inside that ItemTemplate and change the value in the column Total cost in the table by clicking the button? The main problem is that I cannot access the textBox since it's in the . Thank you.
Catalog page:
Cart page:
CartView.aspx
MasterPageFile="~/Page/Store.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="bodyContent" runat="server">
<div id="content" style="margin-left: 7%;">
<style>
#import url("/css/tableCart.css");
#import url("/css/ButtonsCart.css");
</style>
<h2 style="padding: 14px; color:Highlight;">Ваша корзина</h2>
<h3 style="padding: 14px; color:Highlight;">Товары, которые вы добавили в корзину, представлены здесь</h3>
<table id="Table1" V class ="simple-little-table">
<thead>
<tr>
<th></th>
<th>Название</th>
<th>Цвет</th>
<th>Глубина</th>
<th>Ширина</th>
<th>Цена</th>
<th>Количество</th>
<th>Итого</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="Repeater1" ItemType="Line.Models.CartLine"
SelectMethod="GetCartLines" runat="server" EnableViewState="false">
<ItemTemplate>
<tr>
<td><asp:Image ID="Image1" runat="server" style="height:45px; " ImageUrl=<%# Item.Product.Img %> /></td>
<td> <%# Item.Product.NameProduct %> <%# Item.Product.TypeProducts %></td>
<td><%# Item.Product.Colors %></td>
<td>
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<asp:Button ID="cmdUpdate" OnClick="cmdUpdate_Click1" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>'/>
</td>
<td><%# Item.Size.Depth%></td>
<td><%# Item.Product.Price%></td>
</td>
<td>
<td>
<asp:Label ID="Label2" runat="server" Text="<%# ((Item.Quantity *
Item.Product.Price))%>"></asp:Label>
</td>
<td>
<asp:Label ID="txtAmount" runat="server" Text=""></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
<tfoot>
<tr>
<td colspan="3">Итого:</td>
<td colspan="2" ><%= CartTotal.ToString("c") %></td>
</tr>
</tfoot>
</table>
</div>
</asp:Content>
CartView.aspx.cs
using Line.Helpers;
using Line.Models;
using Line.Models.Repository;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Line.Page
{
public partial class CartView : System.Web.UI.Page
{
protected void Page_Load(object sender, RepeaterCommandEventArgs e)
{
}
public IEnumerable<CartLine> GetCartLines()
{
return SessionHelper.GetCart(Session).Lines;
}
public decimal CartTotal
{
get
{
return SessionHelper.GetCart(Session).ComputeTotalValue();
}
}
public string CheckoutUrl
{
get
{
return RouteTable.Routes.GetVirtualPath(null, "checkout",
null).VirtualPath;
}
}
public string ReturnUrl
{
get
{
return SessionHelper.Get<string>(Session, SessionKey.RETURN_URL);
}
}
protected void cmdUpdate_Click1(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items[Convert.ToInt32(e.CommandArgument)];
TextBox tQty = (TextBox)rRow.FindControl("txtQty");
Label tAmount = (Label)rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text;
}
}
}
}
Ok, so you can set the index of the button, and pick this up in the Repeater "item command"
So, for your button, you can/want say this:
I have qty, price, and amount in the repeater. and button.
So, the markup can look like this:
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, you are now free to enter Qty, amount in any of the repeated items.
I have this:
Now, my repeater is going accross - and I think you should be using a listview since that better supports a grid + columnar layout - but it really don't mater (listview, gridview, repeater - they all work the same).
So, note how in our button we have both command Name, and command argument. In command argument I pass the row of the repeater.
So, the code looks like this:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// update button in repeater clicked
// update amount based on qty, and price
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items(e.CommandArgument);
TextBox tQty = rRow.FindControl("txtQty");
TextBox tPrice = rRow.FindControl("txtPrice");
TextBox tAmount = rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text * tPrice.Text;
}
}
So, just pass the "index" of the repeater row as per above. We used this expression as command argument:
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, once you have the Item Index (row index), then you can run code against the one row and change that row as per above.
Edit:
So the full markup I have is this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>' />
<div>
City : <asp:DropDownList ID="cboCity" runat="server" DataTextField="City"
DataValueField="City" Width="110px">
</asp:DropDownList>
<div style="float:right;text-align:center;margin-left:4px;">
<asp:Button ID="cmdAddCity" runat="server" Text="+" OnClick="cmdAddCity_Click" Height="16px" Width="12px" Font-Size="XX-Small" cssclass="btnPad" OnClientClick="AddCity();return false"/>
</div>
</div>
Active: <asp:CheckBox ID="chkActive" runat="server" Checked = '<%# Eval("Active") %>'/>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
The code to load up this repeater is this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
LoadGrid();
}
public void LoadGrid()
{
cmdSQL.Connection.Open();
strSQL = "SELECT ID, FirstName, LastName, HotelName, City, Active from tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
rstTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = rstTable;
Repeater1.DataBind();
}
}
so the above fills out the repeater - as noted, for a grid like layout, I would use a listview. Drag a list view into a web page.
use the wizards to connect to the database. Now blow out all the templates, only leave the itemtemplate.
Your code to load up the grid - same as above.
now, in place of the repeater as per previous screen shots?
You get this:
So your multiple lines that your building? They should be based on and around a listview. And each row can thus be grabbed, and addressed just as I did per above.
Do a google for listview examples - there is a like a billion examples.
Once you have this setup, then each row is a "thing" that repeats for you automatic based on the data from the table.
The markup for the list view - it again quite much follows the same ideas and concepts as a repeator. the listview for above looks like this:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
<ItemTemplate>
<tr style="">
<td><asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td><asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Eval("Active") %>' Enabled="false" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">ID</th>
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">Active</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
Please help me fathom this.
I have created a ListView, displaying data from a SQL database. I have enabled inserting, editing and deleting and it all works.
What do I want?
I want to use SweetAlert to prompt the user to confirm yes/no whether they want to delete the entry from the ListView or not.
What have I done?
First I tried using the "builtin" functionality where I added OnClientClick="return confirm('are you sure')" to the <asp:Button/> calling the delete of the given ListView entry. That worked! When I clicked yes it deleted and no it didn't. I didn't have to do anything other than add the above. But It is not what I want. I want the fancier SweetAlert to be displayed, and here the problem starts.
Second I thought I could simply create the SweetAlert script and call its function name from the button. However when doing so, it does open SweetAlert but before I even get the chance to click yes and no, it has already deleted the item and closes the box.
<script>
function deletealert()
{
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
}
</script>
Now I know that there is no functionality in the above, but I didn't even get the chance to move to the yes and no, it closed the script by itself. Then I found out that I could stop the deleting by setting CausesValidation=false on the delete <asp:Button /> but then nothing happened at all.
Third I think I have a breakthrough, but I have no clue how to finish it. I found out that on the ListView, there is an event called ItemDeleting. This event fires before the delete is executed. I tested it out, and it works.
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true); //Calls the sweetalert
e.Cancel = true;
//e.Cancel = false;
}
If I use the e.Cancel = true; then the item is not deleted and the action is cancelled. If I use the e.Cancel = false; then the item is deleted. So I think I may have to incorporate that functionality with the above jQuery. I don't know if I can put jQuery inside the protected void and work with it from there either?
Updated to include suggested solution from haraman Here is also the entire .aspx page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="forum-front.aspx.cs" Inherits="initial.site.forum_front" EnableViewState="true" EnableEventValidation="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="Content/sweetalert.min.js"></script>
<%--CSS Style Sheets--%>
<link href="Content/Styles.css" rel="stylesheet" />
<link href="Content/StylesPanel.css" rel="stylesheet" />
<link href="Content/sweetalert.css" rel="stylesheet" />
<%--Java Scripts--%>
<script>
function deletealert(ctl) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}, function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
// RESUME THE DEFAULT LINK ACTION
eval(defaultAction);
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
</script>
<asp:Panel ID="Panel1" runat="server" Height="1401px">
<center>
<table>
<tr>
<td>
<asp:Button ID="TilForsiden" runat="server" OnClick="TilForsiden_Click" Text="Forsiden" CssClass="button" />
</td>
<td>
<asp:Panel ID="Panel2" runat="server" CssClass="panel panel-default">
<h1><asp:Label ID="ForumOverskrift" runat="server" CssClass=""></asp:Label></h1>
</asp:Panel>
</td>
</tr>
</table>
</center>
<center>
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" InsertItemPosition="LastItem" DataKeyNames="OpslagsID" OnDataBound="SkrivOpslag_Click">
<AlternatingItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton1" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Rediger" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</AlternatingItemTemplate>
<EditItemTemplate>
<tr style="">
<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="btn-default" />
</td>
<td>
<asp:TextBox ID="IndholdTextBox" runat="server" Text='<%# Bind("Indhold") %>' />
</td>
<td>
<asp:TextBox ID="EmneTextBox" runat="server" Text='<%# Bind("Emne") %>' />
</td>
</tr>
</EditItemTemplate>
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<InsertItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="EmneTextBox" Placeholder="Emne..." runat="server" Text='<%# Bind("Emne") %>' CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" />
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="IndholdTextBox" Placeholder="Skriv her..." runat="server" Text='<%# Bind("Indhold") %>' CssClass="form-control" ToolTip="Skriv dit indhold her" TextMode="MultiLine" Rows="8" Width="500px" />
</td>
</tr>
</table>
<tr style="">
<td>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Udgiv" CssClass="btn-info" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Ryd" CssClass="btn-default" />
</td>
<td></td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr style="">
<td>
<asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton2" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
<asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="" class="table table-striped">
<tr runat="server" style="">
<th runat="server"></th>
<th runat="server">Indhold</th>
<th runat="server">BrugerNavn</th>
<th runat="server">Postnummer</th>
<th runat="server">Emne</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Button ID="SkrivOpslag" runat="server" CommandName="SkrivOpslag" Text="Skriv Opslag" CssClass="btn btn-default btn-xs" OnClick="SkrivOpslag_Click" />
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" FirstPageText="Første Side" ShowLastPageButton="True" LastPageText="Sidste Side" PreviousPageText="Forrige" NextPageText="Næste" ButtonCssClass="btn btn-default" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<SelectedItemTemplate>
<tr style="">
<td>
<asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" CssClass="btn btn-default btn-xs" />
<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" />
</td>
<td>
<asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
</td>
<td>
<asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
</td>
<td>
<asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
</td>
<td>
<asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
</td>
</tr>
</SelectedItemTemplate>
</asp:ListView>
</center>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="True" ConnectionString="<%$ ConnectionStrings:foradbConnectionString %>" DeleteCommand="DELETE FROM [testOpslagstabel] WHERE [OpslagsID] = #OpslagsID" InsertCommand="INSERT INTO [testOpslagstabel] ([Indhold], [DatoTid], [Reference], [BrugerNavn], [Emne], [Postnummer]) VALUES (#Indhold, GetDate(), #Reference, 'testuser', #Emne, #Postnummer)"
SelectCommand="SELECT * FROM [testOpslagstabel] WHERE ([Postnummer] = #Postnummer)" UpdateCommand="UPDATE [testOpslagstabel] SET [Indhold] = #Indhold, [DatoTid] = #DatoTid, [Reference] = #Reference, [BrugerNavn] = 'testuser', [Postnummer] = #Postnummer, [Emne] = #Emne WHERE [OpslagsID] = #OpslagsID"
InsertCommandType="Text">
<DeleteParameters>
<asp:Parameter Name="OpslagsID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Indhold" Type="String" />
<asp:Parameter Name="DatoTid" Type="DateTime" />
<asp:Parameter Name="Reference" Type="Int32" />
<asp:Parameter Name="BrugerNavn" Type="String" />
<asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
<asp:Parameter Name="Emne" Type="String" />
<asp:Parameter Name="OpslagsID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Panel>
</asp:Content>
Just to make everything more clear I'm updating the post with the full code in my code behind the aspx. Also if it makes the understanding better, I'm trying to create a forum.
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace initial.site
{
public partial class forum_front : System.Web.UI.Page
{
string qbynavn;
object objbynavn;
// Makes the SQL connection string
String CS = ConfigurationManager.ConnectionStrings["FORADB"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string qpostnr = Request.QueryString["Postnummer"];
if (qpostnr != null)
{
try
{
using (SqlConnection con = new SqlConnection(CS))
{
// specifies the command to check for zipcode
SqlCommand cmd = new SqlCommand("SELECT Bynavn FROM Postnummertabel WHERE Postnr = " + qpostnr, con);
// Opens the connection
con.Open();
objbynavn = cmd.ExecuteScalar();
qbynavn = objbynavn.ToString();
ForumOverskrift.Text = " Velkommen til " + qbynavn;
}
}
catch (Exception ex)
{
Response.Write("Der opstod en fejl! " + ex.Message);
}
}
else
{
ForumOverskrift.Text = " Velkommen!";
}
}
public void AnswerButton_Click(object sender, EventArgs e)
{
// Tries to bind the sender to the right button.
Button originator = sender as Button;
// Checks if it has been found
if (originator != null)
{
// Goes throug the control hierachy to find the right item.
var parentItem = originator.Parent as ListViewItem;
if (parentItem != null
&& parentItem.ItemType == ListViewItemType.DataItem)
{
// Binds the textbox and button to variables
var textBox = parentItem.FindControl("AnswerTextBox") as TextBox;
var btn = parentItem.FindControl("AnswerButton") as Button;
if (textBox != null)
{
// Changes the textbox to being visible and changes the buttons text.
if (textBox.Visible == false)
{
textBox.Visible = true;
btn.Text = "Fortryd";
}
// Changes the textbox to invisible and changes the buttons text.
else if (textBox.Visible == true)
{
textBox.Visible = false;
btn.Text = "Svar";
}
}
}
}
}
// Makes the Skriv Opslag field either visible or invisible
protected void SkrivOpslag_Click(object sender, EventArgs e)
{
if (ListView1.InsertItem.Visible == true)
{
// Makes the Skriv Opslag field invisible
ListView1.InsertItem.Visible = false;
// Changes the buttons name to Skriv Opslag
Button btn = (Button) ListView1.FindControl("SkrivOpslag");
btn.Text = "Skriv Opslag";
}
else if (ListView1.InsertItem.Visible == false)
{
// Makes the Skriv Opslag field visible
ListView1.InsertItem.Visible = true;
// Changes the Buttons name to Skriv Opslag
Button btn = (Button)ListView1.FindControl("SkrivOpslag");
btn.Text = "Fortryd";
}
}
protected void TilForsiden_Click(object serder, EventArgs e)
{
Response.Redirect("~/welcomepage.aspx");
}
protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true);
//e.Cancel = true;
//Response.Write("<script>deletealert();</script>");
//ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "deletealert();", true);
}
}
}
First you must understand that you can not mix server side code then client side code and then again server code in one go as you are currently doing in ItemDeleting event. All client side code will fire only when the page PostBacks after completing the server side code execution.
Now, with regard to your use of plugin. Have you returned anything from the swal function?
Lets try to do it the old way using your first method OnClientClick="return confirm('are you sure')". Modify it to OnClientClick="return deletealert();". Now in JavaScript return true/false in your deletealert function (focus on comments in CAPITALS)
... YOUR OTHER CODE IN DELETEALERT
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
//RETURN TRUE TO EXECUTE SERVER CODE
return true;
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
//RETURN FALSE TO SKIP SERVER CODE
return false;
}
});
... YOUR OTHER CODE
Update:
The working of SweetAlert is somewhat different from a regular alert. It does shows a modal window but does not prevent any action initiated by the user such as submit, link click. So the workaround is to store the href of the link in a var, show SweetAlert and then use eval to resume that link.
function deletealert(ctl, event) {
// STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
var defaultAction = $(ctl).prop("href");
// CANCEL DEFAULT LINK BEHAVIOUR
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal({ title: "Deleted!", text: "Your imaginary file has been deleted.", type: "success", confirmButtonText: "OK!", closeOnConfirm: false },
function () {
// RESUME THE DEFAULT LINK ACTION
window.location.href = defaultAction;
return true;
});
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
return false;
}
});
}
I have replaced the asp:Button with asp:LinkButton just for easy handling of preventDefault and then resuming the operation.
<asp:LinkButton OnClientClick="return deletealert(this, event);" ID="DeleteButton" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
Only one small glitch needs to be tackled is when the user finally clicks the ConfirmButton the final success message is displayed but at the same time the default action is also executed resulting in a postback. Updated to postback after final success message and FireFox update.
You need to prompt before you get to the server; so attach to the delete button click using jQuery:
$("#idofplaceholderwrappingtheitems").find("[id$='DeleteButton']").on("click", function(e) {
//show confirmation here;
});
Showing the javascript in ItemDeleting is too late in the process.
The error occurs when the asp:ListView object tries to call the update command built in to the datasource. Specifically the error states:
Cannot insert the value NULL into column 'FirstName', table
'SqlCatalog.dbo.Members'; column does not allow nulls. UPDATE fails.
The statement has been terminated
I'm using the following code in the ItemUpdateEventHandler to verify NULL's are not being inserted into fields that are set to NOT NULL.
protected void Members_VerifyChanges(Object sender, ListViewItemUpdateEventArgs eArgs)
{
if(eArgs.NewValues["ID"] == null || eArgs.NewValues["FirstName"] == null || eArgs.NewValues["LastName"] == null)
{
eArgs.Cancel = true;
}
}
Here is the UPDATE command specified for the datasource:
UPDATE Members SET [ID]=original_ID, [Approved]=#App, [FirstName]=#First, [MiddleInitial]=#Mid, [LastName]=#Last WHERE ID=#original_ID
Since the event handler function does not cancel the UPDATE command I can be sure the NewValues dictionary has something other than NULL to be inserted into the FirstName field.
Here is the specific test case I have been working with.
Old Values
________________________________________________________________________________
|____ID____|____Approved____|____First Name____|____Initial____|____Last Name____|
|__1001____|______[x]_______|_______Test_______|_______A_______|______Test_______|
New Values
________________________________________________________________________________
|____ID____|____Approved____|____First Name____|____Initial____|____Last Name____|
|__1001____|______[x]_______|______Bruce_______|_______A_______|______Wayne______|
To me it seems like the NewValues Dictionary is not being added to the parameters but I don't know how I could check that. I've thought about manually creating and executing the update command in the event handler but that's a hack i'd prefer not to do.
Here is the asp markup for the SqlDataSource:
<asp:SqlDataSource ID="WaterFacultySqlDataSrc" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" OldValuesParameterFormatString="original_{0}"
SelectCommand="SELECT [ID], [Approved], [FirstName], [MiddleInitial], [LastName] FROM Members ORDER BY [ID] DESC"
InsertCommand="INSERT INTO [Members] (ID, Approved, FirstName, MiddleInitial, LastName VALUES (#ID, #App, #First, #Mid, #Last)"
UpdateCommand="UPDATE [Members] SET [ID]=#original_ID, [Approved]=#App, [FirstName]=#First, [MiddleInitial]=#Mid, [LastName]=#Last WHERE ID=#original_ID"
DeleteCommand="DELETE FROM [Members] WHERE ID=#original_ID">
<UpdateParameters>
<asp:Parameter Name="ID" Type="Int32" />
<asp:Parameter Name="original_ID" Type="Int32" />
<asp:Parameter Name="App" Type="Boolean" />
<asp:Parameter Name="First" Type="String" />
<asp:Parameter Name="Mid" Type="Char" />
<asp:Parameter Name="Last" Type="String" />
</UpdateParameters>
/**For Brevity I've excluded the other commands parameters*/
and finally the markup for the ListView controller:
<asp:ListView ID="PendingUpdates" runat="server" DataKeyNames="ID" DataSourceID="WaterFacultySqlDataSrc" OnItemUpdating="Members_VerifyChanges">
<LayoutTemplate>
<table id="PendingUpdatesTable" runat="server">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="1"
style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
<tr id="TableHeaders" runat="server" style="background-color: #E0FFFF;color: #333333;">
<th id="ApproveOrDeny" runat="server">
Approve/Deny</th>
<th id="WF_ID_Header" runat="server">
ID</th>
<th id="Approved_Header" runat="server">
Approved</th>
<th id="First_Header" runat="server">
First Name</th>
<th id="Middle_Header" runat="server">
Initial</th>
<th id="Last_Header" runat="server">
Last Name</th>
</tr>
<tr ID="itemPlaceHolder" runat="server">
</tr>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr style="background-color: #E0FFFF;color: #333333;">
<td>
<asp:Button ID="Edit_Button" runat="server" CommandName="Edit" Text="Edit"/>
<asp:Button ID="Delete_Button" runat="server" CommandName="Delete" Text="Delete"/>
</td>
<td>
<asp:Label ID="ID_Val" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:Label ID="Approve_Val" runat="server" Text='<%# Bind("Approved") %>' />
</td>
<td>
<asp:Label ID="First_Val" runat="server" Text='<%# Bind("FirstName") %>' />
</td>
<td>
<asp:Label ID="Middle_Val" runat="server" Text='<%# Bind("MiddleInitial") %>' />
</td>
<td>
<asp:Label ID="Last_Val" runat="server" Text='<%# Bind("LastName") %>' />
</td>
</tr>
</ItemTemplate>
<EditTemplate>
<tr style="background-color: #E0FFFF;color: #333333;">
<td>
<asp:Button ID="Save_Button" runat="server" CommandName="Update" Text="Save"/>
<asp:Button ID="Cancel_Button" runat="server" CommandName="Cancel" Text="Cancel"/>
</td>
<td>
<asp:Label ID="ID_Val" runat="server" Text='<%# Bind("ID") %>' />
</td>
<td>
<asp:checkBox ID="Approve_Val" runat="server" checked='<%# Bind("Approved") %>' />
</td>
<td>
<asp:textBox ID="First_Val" runat="server" Text='<%# Bind("FirstName") %>' />
</td>
<td>
<asp:textBox ID="Middle_Val" runat="server" Text='<%# Bind("MiddleInitial") %>' />
</td>
<td>
<asp:textBox ID="Last_Val" runat="server" Text='<%# Bind("LastName") %>' />
</td>
</tr>
</EditTemplate>
</asp:ListView>
Not sure why but changing the names of 2 of the parameters fixed this error.
UPDATE Members SET [ID]=original_ID, [Approved]=#App, [FirstName]=#FirstName, [MiddleInitial]=#Mid, [LastName]=#LastName WHERE ID=#original_ID}
I'm guessing Microsoft SQL Server 2008 R2 is parsing First and Last as keywords to indicate the chronological First and Last parameters rather than the parameters named First and Last. I've not been able to confirm that, but I'll keep digging and post the answer when I find it.
i have this in source code:
<a href="CreateAlbum.aspx" id="createalbumlink">
Create New Album
</a>
now i want to set its visibility in code behind. How can i do so? I have this link within ListView Control.
I replaced the above with
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
still couldnt detect in codebehind.
SOurce code:
<form id="form1" runat="server">
<asp:ListView ID="lvAlbums" runat="server"
DataSourceID="SqlDataSource1" GroupItemCount="3"
InsertItemPosition="LastItem">
<LayoutTemplate>
<table border="1">
<tr ID="groupPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<td ID="itemPlaceholder" runat="server">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td3" width="150px" height="150px" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:HiddenField ID="hfPhotoID" runat="server" Value='<%# Eval("DefaultPhotID") %>' />
<a href='<%# "Photos.aspx?AlbumID="+Eval("AlbumID") %>'>
<asp:Image CssClass="Timg" runat="server" ID="imPhoto" ImageUrl='<%# "ThumbNail.ashx?ImURL="+Eval("Photo") %>' />
</a>
<br />
<b><asp:Label ID="lblAlbumName" runat="server" Text='<%# Eval("AlbumName") %>'></asp:Label> </b>
</td>
</ItemTemplate>
<InsertItemTemplate>
<td id="Td3" width="150px" height="150px" runat="server" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
<%-- <a href="CreateAlbum.aspx" id="createalbumlink" runat="server">
Create New Album
</a>--%>
</td>
</InsertItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SLIITComDBConnectionString %>"
SelectCommand="SELECT Album.AlbumID, Album.DefaultPhotID, Album.AlbumName, PhotAlbum.Photo FROM Album INNER JOIN PhotAlbum ON Album.DefaultPhotID = PhotAlbum.PhotoID where album.userid=#userid">
<SelectParameters>
<asp:QueryStringParameter Name="userid" Type="int32" QueryStringField="id" />
<%--<asp:SessionParameter Name="userid" Type="String" SessionField="UserId" />--%>
</SelectParameters>
</asp:SqlDataSource>
</form>
Well you can't access the LinkButton directly since its inside a ListView, you can iterate through each item in the ListView and find the link button using FindControl and then set the Visible property. Something like:
foreach (ListViewItem item in listView.Items)
{
LinkButton linkButton = item.FindControl("LinkButton1") as LinkButton;
if (linkButton != null)
linkButton.Visible = false;
}
the above will disable LinkButton for all the items.
Use the OnClick event handler of the LinkButton and toggle the visibility there.
Somewhere in the code behind do this:
LinkButton1.Visible = false;
LinkButton1.Visible = false; //control will not rendered
LinkButton1.Attribute["styles"] = "display:none"; // control will be hidden
You can alse use tag, but you have to add runat="server" param
Edit
Try using FindControl:
LinkButton LinkButton1 = (LinkButton)ListView1.FindControl("LinkButton1");
LinkButton1.Visible = false;
I use web control in asp.net using c#. I use div tag. on btnProviderSubmit1 i change visibility of divprov. but divprov is not visible false. It visible.
pos.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="pos.ascx.cs" Inherits="USerControls_Recharge_pos" %>
<%# Register Assembly="Gaia.WebWidgets" Namespace="Gaia.WebWidgets" TagPrefix="gaia" %>
<form id="Form1" runat="server">
<div>
<div>
<asp:LinkButton runat="server" ID="moveTo" Text="Go To Classical Mode" PostBackUrl="~/DesktopModules/Recharge/Recharge.aspx" OnClick="SaveCookies"/>
</div>
<div title="Select Provider" id="divprov" **visible="true"** runat="server" style="border-width:medium;border-color:Blue;border-width:medium;">
<asp:ListView DataSourceID="ObjectDataSource1" GroupItemCount="12" GroupPlaceholderID="groupPlaceholder" ItemPlaceholderID="itemPlaceholder" ID="ddlprovider" runat="server">
<LayoutTemplate >
<table runat="server" id="table2" style="border-width:medium" cellpadding="3">
<tr runat="server" id="groupPlaceholder">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr runat="server" id="productRow" style="height:80px">
<td runat="server" id="itemPlaceholder">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td2" valign="top" align="center" style="width:100" runat="server">
<gaia:ImageButton runat="server" CommandArgument='<%#Eval("providerID") %>' **OnCommand="btnProviderSubmit1"** ImageUrl='<%# getImageURL(Eval("providerCode")) %>' ID="ImageButton1" /><br />
<gaia:LinkButton runat="server" CommandArgument='<%#Eval("providerID") %>' OnCommand="btnProviderSubmit1" Text='<%#Eval("description") %>' ID="lnkButton1"/>
</td>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DeleteMethod="Delete" InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}" SelectMethod="FetchAll"
TypeName="mogile.MidTier.DAL.ProviderController" UpdateMethod="Update">
</asp:ObjectDataSource>
</div>
<div>
<gaia:Panel runat="server" ID="pnlCircle" Visible="false" ScrollBars="Auto">
<asp:ListView ID="ddlCircle" GroupItemCount="8" GroupPlaceholderID="groupPlaceholder" ItemPlaceholderID="itemPlaceholder" runat="server" DataSourceID="ObjectDataSource2">
<LayoutTemplate>
<table runat="server" id="table2" cellpadding="3">
<tr runat="server" id="groupPlaceholder">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr runat="server" id="tableRow">
<td runat="server" id="itemPlaceholder" />
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td1" runat="server">
<gaia:LinkButton ID="LinkButton1" OnCommand="btnCircleSubmit" Font-Size="Larger" BorderColor="red" BorderWidth="4px" runat="server" CommandArgument='<%#Eval("StateID") %>' Text='<%#Eval("StateName") %>'/>
</td>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
DeleteMethod="Delete" InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}" SelectMethod="FetchAll"
TypeName="mogile.MidTier.DAL.StateController" UpdateMethod="Update">
</asp:ObjectDataSource>
</gaia:Panel>
</div>
</div></form>
pos.ascx.cs
public partial class USerControls_Recharge_pos : System.Web.UI.UserControl
{
private static int itemid = 0;
private static string circleCode;
private static string pdfText;
private static string providerName;
private static string productGrp;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnProviderSubmit1(object sender, CommandEventArgs e)
{
providerName = e.CommandArgument.ToString();
loadProductGroups(e.CommandArgument.ToString());
pnlCircle.Visible = true;
**divprov.Visible = false;**
}
protected void btnCircleSubmit(object sender, CommandEventArgs e)
{
circleCode = e.CommandArgument.ToString();
pnlProductGrp.Visible = true;
// pnlCircle.ForceAnUpdate();
}
}
A workaround could probably be to add "display:none" (or was it "visibility:hidden"? - you can google here) to the style attribute programatically in the btnClick handler.