change date label by user - javascript

I'm using C#.net to program a reservation system
I want to let the user change date through the arrows as shown on the picture (please click on the link)
date image
I have done from displaying the current date on the screen but I just don't know how to let the user use the arrows to change the dates
these are the html codes:
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" style="font-size:30px;" />
and these are the C# code
protected void page_load(object sender, EventArgs e)
{
lblServerDateTime.Text = DateTime.Now.ToString("M");
}

This snippets may help you:
Aspx
<asp:Button Text="Down" ID="btnDown" runat="server" OnClick="btnDown_Click" />
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" Style="font-size: 30px;" />
<asp:Button Text="UP" ID="btnUp" runat="server" OnClick="btnUp_Click" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblServerDateTime.Text = DateTime.Now.ToString("dd MMMM");
calCurrentDay.SelectedDate = DateTime.Now;
// Sets current date on initially.
}
}
protected void btnUp_Click(object sender, EventArgs e)
{
//Up button click will increase the date by one day
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}
protected void btnDown_Click(object sender, EventArgs e)
{
//Up button click will decrease the date by one day
DateTime d;
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(-1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}

Related

How do i close child window in asp.net c#?

I am now creating a web site with webforms in C#. I made a button that opens the child window with a landscape photo if pressed. On top of the landscape painting in the child window, comments written in the parent window are displayed.
The user can press this button to open as many child windows as they press, separate from the ASPX page with this button. Just press the button 10 times to open 10 pages of child windows with pictures of landscape paintings.
What I want to do is not press the button 10 times to create 10 child windows, but I want to update the child window 9 times after the child window is created in the first time.
If possible, I'd like you to tell me how to do it. Also, I thought that it would be difficult for me to do so, so I thought that if I pressed the button after the second time, the old child window created by pressing the button before that would close and a new child window would be born.
Below is the code I wrote.
↓aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
↓aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "OpenNewWindow", "window.open('" + url + "', null);",true);
}
The problem is twofold. One way is to update the child window. The other way is to close the child window. I thought that the line window would be closed with the code below, so I tried it lightly, but the parent window closed and the child window remained.
↓aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string url=string.Format("WebForm1.aspx?q={0:s}",TextBox1.Text);
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "CloseNewWindow", "window.Close('" + url + "', null);",true);
}
What should I do?
I think you best consider having this pop up appear on the CURRENT page.
And now that you want to restrict to "one", then that makes this a WHOLE lot less work.
There are more "dialog" systems then flavors of ice cream to choose from.
but, the two most common are the bootstrap ones, and the one from jQuery.UI.
I find the jQuery.UI VERY easy to work with - and you can control position with much greater ease then bootstrap ones.
And given that you have a SUPER high chance of already having jQuery, then adopting jQuery.UI from the same folks makes all the more sense.
And jQuery.UI dialogs can be "modal", and that means focus can't get out of the dialog until you "ok" or "save" or whatever.
So, lets take a simple GridView. Say we have some rows, and a "image".
When we click on the edit button, we pop a dialog with the picture, and also allow you to edit the comments.
So, our Grid is say this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="cmdView" runat="server" Width="150px"
ImageUrl = '<%# Eval("ImagePath") %>'
OnClick="cmdView_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code on page load is thus this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
SqlCommand cmdSQL = new SqlCommand("SELECT * FROM Fighters");
GridView1.DataSource = MyRstP(cmdSQL);
GridView1.DataBind();
}
And now we have this:
So, the way jQuery.UI works?
You create a simple "div" on the same page, and it will become your "dialog"
You then hide with style=display:none.
So our markup for this "div" to disaplay the picture "big" and edit comments is this
(we drop it below the GV)
So, we have this simple markup to display picture, and let user edit comments for the picture:
<div id="EditOne" runat="server" style="text-align:center;display:none" clientidmode="static">
<br />
<asp:Image ID="Image1" runat="server" width="90%" />
<br />
<h4>Edit Description</h4>
<asp:TextBox ID="txtDescription" runat="server"
TextMode="MultiLine" Columns="90" Height="100px">
</asp:TextBox>
<br />
</div>
<asp:Button ID="cmdSave" runat="server" Text="Save" ClientIDMode="Static"
style="display:none" OnClick="cmdSave_Click"/>
Note careful in above - right below the div, I have a hidden save button.
So, now the jQuery routine that we pop to display this div as a dialog:
this:
<script>
function popimage(btn) {
pWidth = "50%"
myDialog = $("#EditOne");
myDialog.dialog({
title: "Edit Comments",
modal: true,
width: pWidth,
closeText: "",
show: "fade",
buttons: {
Save: function () {
myDialog.dialog("close")
$('#cmdSave').click()
},
Cancel: function () {
myDialog.dialog("close")
}
}
})
}
</script>
So, now we only need our button row click from the grid (I used image button).
That code is this:
We get the current row PK id, pull from database, and fill out the "div", and then pop it:
protected void cmdView_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
GridViewRow gRow = (GridViewRow)btn.NamingContainer;
int PK = (int)GridView1.DataKeys[gRow.RowIndex]["ID"];
SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM Fighters WHERE ID = #ID");
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PK;
DataTable rstFighter = MyRstP(cmdSQL);
Image1.ImageUrl = rstFighter.Rows[0]["ImagePath"].ToString();
txtDescription.Text = rstFighter.Rows[0]["Description"].ToString();
ViewState["rstFighter"] = rstFighter;
Page.ClientScript.RegisterStartupScript(
this.GetType(),"MyEdit","popimage()", true);
}
And now our save button, to send information back to database is this:
protected void cmdSave_Click(object sender, EventArgs e)
{
// Save comments (and other fields back to database)
DataTable rstFigher = (DataTable)ViewState["rstFighter"];
rstFigher.Rows[0]["Description"] = txtDescription.Text;
SaveData(rstFigher, "Fighters");
LoadGrid(); // refresh grid to show any edits
}
So, the results now look like this when I click on a row image:
Note how the web page behind goes "darker gray" and the pop up is model.
So, I would consider jQuery.UI dialogs.
And I did use two helper routines (after all, we don't write the same code over and over to get get a simple data table, right???).
Those two helper routines were:
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void SaveData(DataTable rstData,string sTable)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM " + sTable, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
So, as above shows you have complete control over closing the pop up dialogue, but MUCH more important we can then also with ease update the current page to reflect those changes ( in our example update the description text in our pick list GridView). And with both the grid display and editing on the same page we also require much less code.

c# How to click this submit button?

I'm trying to make a program that makes Visual studio webclients login to kahoot.it, i now am able to enter the required information to login but have no way to click the submit button...
Here is the code of the button:
<button type="submit" class="btn btn-greyscale join ng-binding" blocking="" data-functional-selector="join-button-game-pin">Enter</button>
Kind regards,
Joep van Diessen
private void button1_Click(object sender, EventArgs e)
{
HtmlDocument doc = webBrowser1.Document;
doc.GetElementById("inputSession").SetAttribute("Value", gpin);
}
private void button2_Click(object sender, EventArgs e)
{
HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;
element.text = #"function sayHello() $('button[type=""submit""]').first().submit()";
headElement.AppendChild(scriptElement);
webBrowser1.Document.InvokeScript("sayHello");
}
Assuming jquery
$('button[type="submit"]').first().submit()
Edit #1
element.text = #"function sayHello() { document.getElementsByTagName('form')[0].submit(); }";

Bootstrap JavaScript breaks ASP.NET postback

Seems like registering bootstrap.js to my page prevents all of my server controls, e.g. asp:LinkButtons and asp:Buttons, from triggering a postback.
I have the following C# script in my masterpage. It just registers jQuery 1.11.1 and Bootstrap.js if the user isn't in Design mode in Kentico. Otherwise it just loads jQuery 1.7.1.
If I don't include bootstrap.js, postbacks from my asp:LinkButtons and asp:Buttons occur as normal. Otherwise, there's just no action happening at all. Any ideas what could be happening?
I don't see any console errors in the browser, and I'm absolutely certain that including Bootstrap.js is somehow partially responsible for this behavior, if not entirely. Everything works just find if it's not included (well, besides bootstrap jQuery modules of course).
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// Check for null document
if(CMSContext.CurrentDocument != null)
{
if(CMS.PortalEngine.PortalContext.ViewMode.ToString() == "Design")
{
CMS.GlobalHelper.ScriptHelper.RegisterJQuery(this.Page);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"jquery","<script src=\"//code.jquery.com/jquery-1.11.2.min.js\"><" + "/script>",false);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"bootstrap","<script src=\"/getmedia/453e9ad5-e05c-4fb2-b134-4d9cbd00c917/bootstrap-min.aspx\"><" + "/script>",false);
}
}
}
</script>
That bootstrap.min.js file is just the default bootstrap.min.js file for v3.3.2
CODE IN-FRONT
<%# Control Language="C#" AutoEventWireup="true" CodeFile="IssuesSettings.ascx.cs" Inherits="CustomCode_Dashboard_Issues_Issues" %>
<div class="col-xs-12">
<div class="gap"></div>
<div class="btn-group" data-toggle="buttons">
<asp:LinkButton runat="server" ID="ButtonCompletedProjects" CssClass="btn btn-default btn-xs" OnClick="ButtonCompletedProjectsClicked">Show Completed Projects</asp:LinkButton>
<asp:LinkButton runat="server" ID="ButtonClosedIssues" CssClass="btn btn-default btn-xs" OnClick="ButtonClosedIssuesClicked">Show Closed Issues</asp:LinkButton>
</div>
</div>
CODE BEHIND
public partial class CustomCode_Dashboard_Issues_Issues : System.Web.UI.UserControl
{
// cookie name constants
private const string CookieClosedIssuesName = "Dashboard-Issues-ShowClosedIssues";
private const string CookieCompletedProjectsName = "Dashboard-Issues-ShowCompletedProjects";
// boolean switches
private bool _showClosedIssues;
private bool _showCompletedProjects;
protected void Page_Load(object sender, EventArgs e)
{
SetShowClosedIssues();
SetShowCompletedProjects();
SetButtonStyles();
}
private void SetButtonStyles()
{
if (_showClosedIssues)
{
ButtonClosedIssues.CssClass += " active";
}
else
{
ButtonClosedIssues.CssClass += " inactive";
}
if (_showCompletedProjects)
{
ButtonCompletedProjects.CssClass += " active";
}
else
{
ButtonCompletedProjects.CssClass += " inactive";
}
}
private void SetShowCompletedProjects()
{
if (Request.Cookies[CookieCompletedProjectsName] != null)
{
_showCompletedProjects = Convert.ToBoolean(Request.Cookies[CookieCompletedProjectsName].Value);
}
else
{
_showCompletedProjects = false;
}
}
private void SetShowClosedIssues()
{
if (Request.Cookies[CookieClosedIssuesName] != null)
{
_showClosedIssues = Convert.ToBoolean(Request.Cookies[CookieClosedIssuesName].Value);
}
else
{
_showClosedIssues = false;
}
}
protected void CLICKER(object sender, EventArgs e)
{
Response.Write("stuff");
}
protected void ButtonClosedIssuesClicked(Object sender, EventArgs e)
{
Response.Write("TEST");
// if we're turning this off
if (_showClosedIssues)
{
HttpCookie cookie = Request.Cookies[CookieClosedIssuesName];
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Value = "False";
Response.Cookies.Set(cookie);
}
// if we're turning this on
else
{
HttpCookie cookie;
if (Request.Cookies[CookieClosedIssuesName] != null)
{
cookie = Request.Cookies[CookieClosedIssuesName];
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
else
{
cookie = new HttpCookie(CookieClosedIssuesName);
cookie.Name = CookieClosedIssuesName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
}
Response.Redirect(CMSContext.CurrentDocument.AbsoluteURL);
}
protected void ButtonCompletedProjectsClicked(Object sender, EventArgs e)
{
// if we're turning this off
if (_showCompletedProjects)
{
HttpCookie cookie = Request.Cookies[CookieCompletedProjectsName];
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Value = "False";
Response.Cookies.Set(cookie);
// change style of button
ButtonCompletedProjects.CssClass.Replace("active","inactive");
}
// if we're turning this on
else
{
HttpCookie cookie;
if (Request.Cookies[CookieCompletedProjectsName] != null)
{
cookie = Request.Cookies[CookieCompletedProjectsName];
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
ButtonCompletedProjects.CssClass.Replace("inactive", "active");
}
else
{
cookie = new HttpCookie(CookieCompletedProjectsName);
cookie.Name = CookieCompletedProjectsName;
cookie.Domain = ".domain.com";
cookie.Expires = DateTime.MaxValue;
cookie.Value = "True";
Response.Cookies.Set(cookie);
}
}
Response.Redirect(CMSContext.CurrentDocument.AbsoluteURL);
}
}
The problem is that the button.js plugin calls preventDefault() on an element with the data-toggle="buttons" data attribute, and the <asp:LinkButton> server control places its '_doPostBack' function call within the href="" attribute of the anchor tag it renders. Therefore the button.js plugin prevents the postback from happening.
I just copy/pasted the markup from the bootstrap docs so I happened to have that attribute on my <div class="btn-group">:
<div class="btn-group" data-toggle="buttons">
<asp:LinkButton runat="server" ID="ButtonCompletedProjects" CssClass="btn btn-default btn-xs" OnClick="ButtonCompletedProjectsClicked">Show Completed Projects</asp:LinkButton>
<asp:LinkButton runat="server" ID="ButtonClosedIssues" CssClass="btn btn-default btn-xs" OnClick="ButtonClosedIssuesClicked">Show Closed Issues</asp:LinkButton>
</div>
The server controls render the following markup:
<div class="btn-group" data-toggle="buttons">
<a id="p_lt_ctl01_pageplaceholder_p_lt_ctl02_IssuesSettings_userControlElem_ButtonCompletedProjects" class="btn btn-default btn-xs" href="javascript:__doPostBack('p$lt$ctl01$pageplaceholder$p$lt$ctl02$IssuesSettings$userControlElem$ButtonCompletedProjects','')">Show Completed Projects</a>
<a id="p_lt_ctl01_pageplaceholder_p_lt_ctl02_IssuesSettings_userControlElem_ButtonClosedIssues" class="btn btn-default btn-xs" href="javascript:__doPostBack('p$lt$ctl01$pageplaceholder$p$lt$ctl02$IssuesSettings$userControlElem$ButtonClosedIssues','')">Show Closed Issues</a>
</div>
Notice how _doPostBack is within the href attribute on both anchor elements. Now, checkout the button.js plugin, you'll see the following lines:
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() // here's the issue
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
On line 9 (starting from //BUTTON DATA-API) you'll see e.preventDefault() being called at the end of the if statement. This is going to prevent the anchor tag from performing its default behavior, which would be to call the _doPostBack function.
If you're having this issue and don't need the button plugin, just remove that plugin from your script. If you do need the button plugin and are having this issue, you'll need to write some logic to handle this. I modified that if statement on line 9 to check for the '.btn-asp' class first and to proceed with default behavior if that was the case, otherwise it proceeds with the button plugin's logic:
if(!($e.target).hasClass(".btn-asp")){
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault() // here's the issue
}

How to call javascript from code behind for Repeater control

There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Categories