Trying to print the stored data of arraylist to the gridview.
.aspx File, Working perfectly fine.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Stock Management System</title>
<style>
body{
background-color:#63AA9C;
text-align:center
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" style="background-color:lightcoral">
<tr><td>Item Name:</td><td><asp:TextBox ID="Name" placeholder="Item Name" runat="server"></asp:TextBox></td></tr>
<tr><td>Quantity:</td><td><asp:TextBox ID="Quan" placeholder="Quantity" runat="server"></asp:TextBox></td></tr>
<tr><td>Price:</td><td><asp:TextBox ID="Pri" placeholder="Price" runat="server"></asp:TextBox></td></tr>
<tr><td>Description:</td><td><asp:TextBox ID="Desc" placeholder="Descrition" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="Save" runat="server" Text="Store Data" OnClientClick="Store()" width="200px"/></td></tr>
<tr><td><asp:Button ID="Show" runat="server" Text="Show Data" OnClientClick="Print()" width="200px" /></td></tr>
<tr><td><asp:Button ID="Delete" runat="server" Text="Remove Last Added Data" OnClientClick="Remove()" width="200px" /></td></tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
</div>
</form>
</body>
</html>
.aspx.cs File
No error, but not working while pressing the show data button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList items = new ArrayList();
ArrayList price = new ArrayList();
ArrayList quantity = new ArrayList();
ArrayList description = new ArrayList();
static int a = 0;
protected GridView GridView1;
protected GridView GridView2;
protected GridView GridView3;
protected GridView GridView4;
protected void Page_Load(object sender, EventArgs e)
{
}
public void Store()
{
items.Add(Name.Text);
price.Add(Pri.Text);
quantity.Add(Quan.Text);
description.Add(Desc.Text);
a++;
}
public void Print()
{
GridView1.DataSource = items;
GridView1.DataBind();
GridView2.DataSource = quantity;
GridView2.DataBind();
GridView3.DataSource = price;
GridView3.DataBind();
GridView4.DataSource = description;
GridView4.DataBind();
}
public void Remove()
{
if (a > 0)
{
items.RemoveAt(a);
a--;
}
}
}
}
My page, Trying to show stored data
About the attribute OnClientClick you are using, The documentation says
Gets or sets the client-side script that executes when a Button control's Click event is raised.
which means you are trying to execute a JavaScript function called "Print" in your code (same goes with other buttons).
You should check Button.Click event instead.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click(v=vs.110).aspx
Related
===================
UPDATE: 29/06/2017
I am trying to get the delete button within my repeater control to function as intended. The aim is to get the button to "fire" the stored procedure within my MSSQL database.
I would like to thank Win for his in-depth response although I am still struggling to resolve the issue. I accept that I was perhaps unable to articulate my question correctly in the first instance. I have therefore edited my post to show the code I have now. I am confident that I am close to cracking the issue and would sincerely appreciate any assistance.
Code within my *.*aspx page:
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM
[Comments] WHERE ([Ad_ID] = #Ad_ID) ORDER BY [CommentCreationDateTime] ASC">
And further down the *.*aspx page:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2"
Visible="True" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table id="displayCommentsTable" class="displayCommentsTable">
<tr class="displayCommentsTable"><td class="displayCommentsTable">
<asp:ImageButton ID="deleteCommentImageButtonReal" runat="server"
class="rightCross" ImageUrl="images/Red-Cross-Mark-PNG.png"
OnClientClick="return confirm('Are you sure you wish to delete this
comment?');" Height="11" Width="11" CommandName="Delete"
CommandArgument='<%# Eval("Comment_ID") %>' /><%# Eval("CommenterName") %>
commented on <%# Eval("CommentCreationDateTime", "{0:d/M/yyyy <i> hh:mm:ss
tt}") %>
</td></tr>
<tr class="displayCommentsTable"><td class="displayCommentsTable"><%#
Eval("CommentText") %><br /></td></tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And finally, my code behind where the magic should be happening but isn't:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
DeleteCommentById(Convert.ToInt32(e.CommandArgument))
}
}
private void DeleteCommentById(int Comment_ID)
{
SqlConnection conn;
SqlCommand deleteCommentById;
string connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
deleteCommentById = new SqlCommand("usp_deleteCommentById", conn);
deleteCommentById.CommandType = System.Data.CommandType.StoredProcedure;
deleteCommentById.Parameters.Add("#Comment_ID", System.Data.SqlDbType.Int);
deleteCommentById.Parameters["#Comment_ID"].Value = Comment_ID;
conn.Open();
deleteCommentById.ExecuteNonQuery();
conn.Close();
}
It is perhaps worth mentioning that if I "hard code" the line I am attempting to delete then it works. For example, if I used the following within my delete button:
CommandArgument='44'
then the stored procedure would fire and affect line 44 as intended.
Easiest way is to use ItemCommand event.
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="RepeaterDemo.aspx.cs" Inherits="DemoWebForm.RepeaterDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater ID="Repeater1" OnItemCommand="Repeater1_ItemCommand" runat="server">
<ItemTemplate>
<p>
<%#Eval("Name") %>
<asp:ImageButton CommandArgument='<%# Eval("Id") %>' runat="server"
ImageUrl="~/Images/Delete.png" CommandName="Delete" />
</p>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DemoWebForm
{
public partial class RepeaterDemo : System.Web.UI.Page
{
public class Comment
{
public int Id { get; set; }
public string Name { get; set; }
}
public static IList<Comment> Comments = new List<Comment>
{
new Comment {Id = 1, Name = "One"},
new Comment {Id = 2, Name = "Two"},
new Comment {Id = 3, Name = "Three"}
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Repeater1.DataSource = Comments;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
var comment = Comments.FirstOrDefault(c => c.Id == id);
Comments.Remove(comment);
Repeater1.DataSource = Comments;
Repeater1.DataBind();
}
}
}
}
In what event are you trying to access the repeater button?
You will need to try to find the control inside the repeater item.
For eg:
Button btn1 = (Button)rptItem.FindControl("btn1");
Everything was working fine but as I had not specified to only return results that had not been soft deleted, everything was getting returned. Noob mistake, learnt something for the future!
I'm hoping someone can help me as I'm beating my head against a wall trying to figure out the problem. I have a databound CheckboxList that has the SelectedIndexChanged event wired up. AutoPostBack is equal to true and ViewStateMode and EnableViewState are set to "Enabled" and "True" respectively. I have other controls on this same page with server side events that fire just fine with no issue.
The weird thing is, the event SEEMS to be firing, as I can see the page reload when I check one of the items in the list. However, when I set a debug point on the method, the debugger never breaks into that section and none of my code is firing (I've even tried having it write out silly messages just to see if the method is even firing - it's not). Here's the markup:
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
Here's the SelectedIndexChanged event:
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all the things
}
What am I missing? I feel like it must be something obvious but for the life of me, I can't see it.
Also I should note this is in the latest version of Mono so there might be some weird quirk there that's causing the issue.
One final note, there are no errors in the console if I check the browser developer tools so I don't have any weird javascript stuff going on that's causing an issue.
Update
Since it's been asked, I'm posting the entire page markup and the requisite codebehind.
Markup:
<%# Page Language="C#" MasterPageFile="~/pages/master/main.master" Inherits="Letters.Web.UI.searchLetters" AutoEventWireup="true" %>
<asp:Content runat="server" ContentPlaceHolderID="additionalCSS">
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/letters.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/font-awesome.min.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap-multiselect.css") %>" />
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="additionalJS">
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap-multiselect.js") %>">
</script>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="mainContent">
<section id="search-header">
<div class="column">
<div class="field-set">
<asp:Label id="lblTextString" runat="server" CssClass="data-label">Search for Letters</asp:Label>
<div class="data-control">
<asp:TextBox id="txtTextString" Width="100%" runat="server" CssClass="form-control searchable" placeholder="Contains Text" data-paramname="textString" />
</div>
</div>
</div>
<div class="column-small">
<div class="field-set">
<span class="data-label"> </span>
<div class="data-control">
<button id="btnSearch" runat="server" class="search-nav-buttons" onserverclick="Search_Click">
Search
</button>
</div>
</div>
</div>
</section>
<asp:PlaceHolder id="plcSearchResults" runat="server">
<section id="search-results">
<div class="filter-options">
<table>
<tbody>
<tr class="searchresults-headerstyle">
<th scope="col" class="header">Filter Options</th>
</tr>
</tbody>
</table>
<asp:Panel id="pnlLanguage" runat="server">
<h1>Languages</h1>
<asp:HiddenField id="hdlLanguages" runat="server" />
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
</asp:Panel>
</div>
<asp:GridView id="grvResults" runat="server" CssClass="table table-striped table-bordered" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" Width="70%" GridLines="None"
OnPageIndexChanging="GridView_PageIndexChanging" >
<HeaderStyle CssClass="searchresults-headerstyle" />
<FooterStyle CssClass="searchresults-footerstyle" />
<PagerStyle CssClass="pagination-style" />
<Columns>
<asp:TemplateField HeaderText="Search Results" >
<ItemTemplate>
<div class="search-result-record">
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("LetterUrl") %>' Text='<%# Letters.Tools.WebUtils.HtmlEncode(Eval("Title").ToString()) %>' />
<span>(<%# Eval("Language") %>)</span>
<span class="keywords">Keywords: <%# Eval("Categories") %></span>
<asp:Label runat="server" CssClss="language" Visible='<%# Eval("LCID").ToString() != "en" %>'>Language: <%# Eval("Language") %></asp:Label>
<div class="search-abstract">
<%# Eval("SearchAbstract") %>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</section>
</asp:PlaceHolder>
</asp:Content>
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Letters.Domain.Objects;
using Letters.Tools;
namespace Letters.Web.UI
{
public partial class searchLetters : System.Web.UI.Page
{
#region eventhandlers
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack) {
this.BindResults ();
}
}
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grvResults.PageIndex = e.NewPageIndex;
this.BindResults ();
}
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.chkLanguages);
this.FilterResults ();
}
protected void Search_Click(object sender, EventArgs e)
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
#endregion
private void FilterResults()
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (pnlLanguage.Visible) {
parameters.Add (this.chkLanguages.Attributes ["data-paramname"].ToString (), this.GetSelectedItems (this.chkLanguages));
}
//Finally, add the search string
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
private string[] GetFilterOption(string delimitedValue)
{
string[] result = null;
if (delimitedValue.Contains (",")) {
result = delimitedValue.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
} else
result = new string[] { delimitedValue };
return result;
}
private string GetSelectedItems(CheckBoxList list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private string GetSelectedItems(ListBox list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private void PopulateFilters(List<SearchResult> results)
{
var languages = (from x in results
group x by new { x.LCID, x.Language } into counts
select new { Key = counts.Key.LCID, DisplayName = string.Format("{0} ({1})", counts.Key.Language, counts.Count()) }
).ToList();
this.chkLanguages.DataSource = languages;
this.chkLanguages.DataTextField = "DisplayName";
this.chkLanguages.DataValueField = "Key";
this.chkLanguages.DataBind ();
if (!string.IsNullOrEmpty (hdlLanguages.Value)) {
string[] languageSelect = this.GetFilterOption (hdlLanguages.Value);
foreach (ListItem item in this.chkLanguages.Items) {
if (languageSelect.Contains (item.Value))
item.Selected = true;
}
}
}
private void BindResults()
{
List<SearchResult> results = this.GetSearchResults ();
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void BindResults(Dictionary<string, object> parameters)
{
List<SearchResult> results = this.GetSearchResults(parameters);
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void RegisterEvents()
{
this.grvResults.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler (GridView_PageIndexChanging);
}
private List<SearchResult> GetSearchResults()
{
return LetterService.GetSearchResults ();
}
private List<SearchResult> GetSearchResults(Dictionary<string, object> parameters)
{
return LetterService.GetSearchResults (parameters);
}
}
}
I was never able to find the exact cause to the problem. Every other type of control was able to post back events and I could properly handle their events server-side. I ended up working around this particular issue by ripping out the CheckBoxList and replacing it with a gridview that used an item template to store the value in a hidden field and display the checkbox where I could then handle the OnCheckedChanged event (see code below). This worked brilliantly.
Markup
<asp:GridView id="grvLanguages" runat="server" ShowHeader="false" ShowFooter="false" AllowPaging="false"
AllowSorting="false" GridLines="None" AutoGenerateColumns="false" data-paramname="languages" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField id="hdlValue" runat="server" Value='<%# Eval("Key") %>' />
<asp:CheckBox id="chkDisplay" runat="server" Text='<%# Eval("DisplayName") %>' OnCheckedChanged="chkLanguage_SelectedIndexChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void chkLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.grvLanguages);
this.FilterResults ();
}
I'm guessing the problem is probably some weird, esoteric bug in the Mono framework. Like I said, I don't have a problem with ANY other controls (I tested quite a few - all of their server side events handled just fine); it was just a problem with the CheckBoxList.
I want to make Datalist with linkable items that I can Navigate to specific url when i click on it it go to c# do respond to new URL
My Urls aren't constant
how?
you should edit the item template of the DataList and put an ASP HyperLink inside, and you use data binding to assign the NavigateUrl to such control.
something like this:
<asp:DataList ID="listSearchResults" Border="1" BorderColor="Black"
RepeatDirect="Horizontal" RepeatColumns="5" runat="server" >
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("Url") %>' Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:DataList>
another approach is to use ASP:LinkButton and assign CommandName and CommandArgument properties to that control.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Datalist with linkable items</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:DataList ID="dlLinkable" runat="server"
onitemdatabound="dlLinkable_ItemDataBound" >
<ItemTemplate>
<table style="width: 300px;" cellpadding="0" cellspacing="1">
<tr>
<td style="width:200px">
<asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
</td>
<td>
<a id="linkA" runat="server">link</a>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
populateDataList();
}
private void populateDataList()
{
dt = new DataTable();
//Create 3 columns for this DataTable
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Url");
//Add All These Columns into DataTable table
dt.Columns.Add(col1);
dt.Columns.Add(col2);
dt.Columns.Add(col3);
// Create a Row in the DataTable table
DataRow row = dt.NewRow();
row[col1] = 1;
row[col2] = "google";
row[col3] = "http://www.google.com";
dt.Rows.Add(row);
//////////////////////
row = dt.NewRow();
row[col1] = 2;
row[col2] = "yahoo";
row[col3] = "http://www.yahoo.com";
dt.Rows.Add(row);
//////////////////////////////////
dlLinkable.DataSource = dt;
dlLinkable.DataBind();
}
protected void dlLinkable_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
Label lblName = (Label)e.Item.FindControl("lblName");
if (lblName != null)
{
lblName.Text = dt.Rows[e.Item.ItemIndex]["Name"].ToString();
}
HtmlAnchor linkA = (HtmlAnchor)e.Item.FindControl("linkA");
if (linkA != null)
{
linkA.HRef = dt.Rows[e.Item.ItemIndex]["Url"].ToString();
}
}
}
}
I have an ASP .NET page with both asp .net validators and some javascript checking too.
I am advancing into the button code behind:
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
/// ...
Even when the validation fails!
The Page.IsValid check solves it, but it also resets all the JavaScript variables… May there be a way not to advance into the button code?
I have an ajax update panel and some image buttons on the page too… Anything I may look out for?
Thanks in advance!
Here is my aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm2.aspx.cs"
Inherits="WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 500px;">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
var nrOptions = 0;
alert(nrOptions + " - variable initialized");
function IncrementQuantity() {
nrOptions++;
alert(nrOptions);
}
function DecrementQuantity() {
nrOptions--;
alert(nrOptions);
}
function MoreThanTwo() {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
return true;
}
else {
alert('error - must have at least two options, you only have: ' + nrOptions);
return false;
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
Fill in with two or more options:<br />
<table border="1" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="middle">
</td>
<td valign="middle">
Description:
<asp:TextBox ID="TBox1" runat="server" Width="120px" Text='<%# Eval("Desc")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TBox1"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
Points:
<asp:TextBox ID="TBox2" runat="server" Width="20px" Text='<%# Eval("Pont")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TBox2"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="ImageButton1" runat="server" Text="x" CommandName="DeleteRow" OnClientClick="DecrementQuantity();" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TBox2"
ValidationExpression="\d+" ValidationGroup="InsertVal" runat="server"
ErrorMessage="Number >= 0."></asp:RegularExpressionValidator>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td colspan="2" align="right">
<asp:Button ID="lnkAddRow" runat="server" Text="Add option" OnClientClick="IncrementQuantity();"
CommandName="AddRow" OnClick="lnkAddRow_Click" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<p style="text-align: right;">
<asp:Button ID="Button2" runat="server" Text="Save" OnClick="Button2_Click" OnClientClick="return MoreThanTwo();"
ValidationGroup="InsertVal" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
And my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DTable = EmptyDTOptions();
Repeater1.DataSource = DTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRow")
{
DTable.Rows.Add(0, "", "");
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
if (e.CommandName == "DeleteRow")
{
int idx = e.Item.ItemIndex;
DTable.Rows.RemoveAt(idx);
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
}
protected void lnkAddRow_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
int idx = item.ItemIndex;
TextBox tb1 = (TextBox)item.FindControl("TBox1");
TextBox tb2 = (TextBox)item.FindControl("TBox2");
DTable.Rows[idx]["Desc"] = tb1.Text;
DTable.Rows[idx]["Pont"] = tb2.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// save!
}
}
private DataTable DTable
{
get
{
DataTable _dt = (DataTable)Session["DTable"];
if (Object.Equals(_dt, null))
{
_dt = EmptyDTOptions();
Session.Add("DTable", _dt);
}
return _dt;
}
set
{
Session["DTable"] = value;
}
}
DataTable EmptyDTOptions()
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("OptionNr", System.Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dc = new DataColumn("Desc");
dt.Columns.Add(dc);
dc = new DataColumn("Pont");
dt.Columns.Add(dc);
return dt;
}
}
I think it shows what I'm trying to avoid... Advancing to the button2_click with the failed validation (and resetting the javascript variable)... In order to get a list of two or more pairs of items, one of them being a number.
Rather than calling your function from the OnClientClick on the button, you can add a CustomValidator that calls your JavaScript function.
<asp:CustomValidator ID="CheckMoreThanTwo" runat="server"
ValidationGroup="InsertVal"
ClientValidationFunction="MoreThanTwo" />
Then, modify your JavaScript function as follows:
function MoreThanTwo(source, arguments) {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
arguments.IsValid=true;
} else {
alert('error - must have at least two options, you only have: '
+ nrOptions);
arguments.IsValid=false;
}
}
Doing this allows your custom JavaScript validation to work with all the validation code that ASP.NET uses. For instance, if you change to a validation summary, or change validation groups, this custom validator will continue to work the way the rest of the validators work.
.html
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="dark.css" rel="stylesheet" type="text/css" id="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Label ID="CaptionLabel" runat="server"></asp:Label>
<asp:TextBox ID="NumberTextbox" runat="server">(empty)</asp:TextBox>
<asp:Button ID="SquareButton" runat="server" Text="Square" style="background-color:Blue; color:White;" />
<asp:Label ID="ResultLabel" runat="server" Text="(empty)" CssClass="reverse"></asp:Label>
<p>
<asp:Label ID="Label1" runat="server" CssClass="footer1"
Text="Label Label Label Label LabelLabelLabel Label Label Label Label Label Label Label"></asp:Label>
</p>
<asp:RadioButton ID="radioDark" runat="server" AutoPostBack="True"
Checked="True" GroupName="grpSelectStylesheet"
oncheckedchanged="SwitchStylesheets" Text="Dark" />
<br />
<asp:RadioButton ID="radioLight" runat="server" AutoPostBack="True"
GroupName="grpSelectStylesheet" oncheckedchanged="SwitchStylesheets"
Text="Light" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
</html>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SwitchStylesheets(object sender, EventArgs e)
{
if (radioDark.Checked)
stylesheet.Href = "dark.css";
if (radioLight.Checked)
stylesheet.Href = "light.css";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count=DateTime.Now.Second;
for (int i = 0; i < count; i++)
{//for
Label q = new Label();
q.ID = DateTime.Now.Second.ToString();
q.Text = DateTime.Now.Second.ToString();
string spacee = "<br />";
Label space = new Label();
space.Text = spacee;
form1.Controls.Add(q);
form1.Controls.Add(space);
}//for
}
}
When the button is clicked, it works as it should but the footer does not register the expansion of the page.
Your code is completely wrong. you cannot change the stylesheet like this for a control even if the autopostback is set to true.
UPDATE: Here's how you should do it:
1- Remove the .css reference from your page.
2- Add this method to your page:
private void UpdateStylesheet(string filepath)
{
HtmlLink newStyleSheet = new HtmlLink();
newStyleSheet.Href = filepath;
newStyleSheet.Attributes.Add("type", "text/css");
newStyleSheet.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(newStyleSheet);
}
3- Add this line to your page_load event:
UpdateStylesheet("dark.css");
4- Handle the SwitchStylesheets like this:
if (radioDark.Checked)
UpdateStylesheet("dark.css");
if (radioLight.Checked)
UpdateStylesheet("light.css");