Select Day, Month and Year Date from DropDownList in C# - c#

I use this code for populate my own Day, Month and Year Date Selector using three DropDownList in ASP.Net
Now I need set as default value for each DDL the vakue of DateTime.MinValue, that is 01/01/0001 , because the value of date to be recorded in the database is not always available :
in DDL ddlday I need as default value : 01;
in DDL ddlMonth I need as default value : January;
in DDL ddlYear I need as default value : 0001;
Using this code I don't have error but :
in DDL ddlday I have as default value : 01;
in DDL ddlMonth I have as default value : january;
in DDL ddlYear I have as default value : 2019;
Please can you help me ?
My code below.
code-behind
using System;
using System.Collections.Generic;
using System.Globalization;
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)
{
if (!IsPostBack)
{
DateTime dateofBirth = DateTime.MinValue;
ddlMonth.DataSource = Enumerable.Range(1, 12).Select(a => new
{
MonthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(a),
MonthNumber = a
});
ddlMonth.DataBind();
ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse();
ddlYear.DataBind();
ddlday.SelectedValue = dateofBirth.Day.ToString();
ddlMonth.SelectedValue = dateofBirth.Month.ToString();
ddlYear.SelectedValue = dateofBirth.Year.ToString();
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
ddlday.DataSource = Enumerable.Range(1, DateTime.DaysInMonth(DateTime.Now.Year, Convert.ToInt32(ddlMonth.SelectedValue)));
ddlday.DataBind();
}
}
Markup
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sc" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td>
<asp:UpdatePanel ID="updpnlDay" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddlday" runat="server">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="updpnlMonth" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="ddlMonth" runat="server" AutoPostBack="true" DataTextField="MonthName"
DataValueField="MonthNumber" OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:DropDownList ID="ddlYear" runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

but your ddlYear doesn't have value 1, only years in the range from 1920 to 2019.
Did you mean to include min year in the range?
ddlYear.DataSource = Enumerable.Range(DateTime.Now.Year - 99, 100).Reverse().Append(1);

Related

I need to check whether the data entered in form exists in database or not and if it exists redirect it to another page

My short query is that i need to check the login form data that the value entered in name by user to be checked against all the values under column name in the database using LINQ query expression only and if it exists i want to select that particular row to which the name field matches with and redirect the user to another Dashboard page.
Below is the code which stores and selects the row if the record is found in the database into a variable query.Now it's not able to check whether the variable in query points to any row if selected or not of the database table.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SessionHandling.aspx.cs" Inherits="WebApplication5.SessionHandling" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
THIS IS LOGIN FORM
</h1>
Name:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<br />
<br />
E-mail:
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class SessionHandling : System.Web.UI.Page
{
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
tblContact tb = new tblContact();
var query = from x in db.tblContacts where x.name == txtName.Text select x;
}
}
}
Did you try this from your C# code?
if (query.Any())
{
Response.Redirect("http://www.microsoft.com")
}
else
{
Response.Redirect("http://www.google.com")
}

Showing countdown timer on a button

I find a code for setting countdown timer but it only shows minutes not seconds when page is load and also I want that when user click on button then countdown should start and also time (e.g 10:59) should be shown on the clicked button.
Following is the code:
aspx code (ASP.net C#)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Reservation.aspx.cs" Inherits="Reservation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManagerTimer" runat="server"></asp:ScriptManager>
<asp:Timer ID="timer1" runat="server" Interval="1000" OnTick="timer1_tick"></asp:Timer>
<asp:UpdatePanel id="updPnl"
runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="btnTimer" runat="server" BackColor="#05CC00" Height="35px" Text="Reserve" Width="89px" style="border-radius:8px" OnClick="btnTimer_Click"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer1" EventName ="tick" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
aspx.cs code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Reservation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!ScriptManagerTimer.IsInAsyncPostBack)
Session["timeout"] = DateTime.Now.AddMinutes(10).ToString();
}
protected void timer1_tick(object sender, EventArgs e)
{
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
btnTimer.Text = ((Int32)DateTime.Parse(Session["timeout"].
ToString()).Subtract(DateTime.Now).Minutes).ToString();
}
}
}
if (0 > DateTime.Compare(DateTime.Now,
DateTime.Parse(Session["timeout"].ToString())))
{
btnTimer.Text = ((Int32)DateTime.Parse(Session["timeout"].
ToString()).Subtract(DateTime.Now).Minutes).ToString("HH:mm:ss");
}
TimeSpan.ToString() offers a variety of string formats. More info : MSDN
:)

Issue in parsing HTML table to ASP.NET

I am using HtmlAgilityPack to parse a table on html page to ASP.NET but I am getting exception every time.
Code for ASP.NET Page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="httprequest_web.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<hr />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" MaxLength="6" TextMode="Number"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label3" runat="server" Text="Label" Visible="False"></asp:Label>
<hr />
<br />
<asp:Label ID="Label4" runat="server" Text="Label" Visible="False"></asp:Label>
<br />
</div>
</form>
</body>
</html>
CS Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using HtmlAgilityPack;
namespace httprequest_web
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Text = "Train Running Status/ JSON Output";
Label2.Text = "Please enter Train No.:";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//Generation of HTTP request from the train number specified in text box.
try
{
Label3.Visible = false;
//get request
string base_url = "http://railenquiry.in/runningstatus/";
string url_request = string.Concat(base_url, TextBox1.Text);
//using HtmlAgilityPack
WebClient rq = new WebClient();
string getdata = rq.DownloadString(url_request);
HtmlAgilityPack.HtmlDocument rec_data = new HtmlAgilityPack.HtmlDocument();
rec_data.LoadHtml(getdata);
List<List<string>> table = rec_data.DocumentNode.SelectSingleNode("//table[#class='table table-striped table-vcenter table-bordered table-responsive']")
.Descendants("tr").Where(tr => tr.Elements("td").Count() >= 1).Select(tr => tr.Elements("td").Select(td => td.InnerText.Trim()).ToList()).ToList();
}
catch
{
Label3.Visible = true;
Label3.Text = "Something went wrong. Please try again!";
}
}
}
}
HTML Page Source: Click Here
I am trying to parse running status information to display it on my webpage but every time I am getting an null object exception. Please tell me where I am doing it wrong. Thanks in advance!
HttpClient client = new HttpClient();
var html = await client.GetStringAsync("http://railenquiry.in/runningstatus/12736");
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
//Same as in your question
var table = doc.DocumentNode.SelectSingleNode("//table[#class='table table-striped table-vcenter table-bordered table-responsive']");
var result = table.Descendants("tr")
.Select(tr => tr.Descendants("td").Select(td => td.InnerText).ToList())
.Skip(1) //Skip headers
.Where(x => x.Count==11) //Skip the footer row
.ToList();
result will be List<List<string>> as you expect in your question.

Use asp.net button onclick method instead of submitting form

I have an asp.net Button control which I want to use to insert comments in my page. When i click on button, I want it to call a method instead of submitting the form. How do i achieve this?
This is what i have tried so far -
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
//Do some stuff here
}
</script>
<head>title and other css links go here</head>
<body>
<form id="form1" runat="server" onsubmit="false">
//Some other asp.net controls go here
<asp:Button ID="Button1" runat="server" Text="Comment" OnClick="Button1_Click"/>
</form>
</body>
</html>
Is there any other way to achieve what I am doing? Suggestions are welcome.
I don't really know exactly what you are meaning.... I think you are asking for how to insert a comment into an aspx via a shout box???... Maybe?
Here is the code to insert whatever you want to type(a comment) into your form from a "method"... although it uses a lot more than just a single method.. this is the simplest way I can think of...
This is your default.aspx (notice no master page here)
<!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 id="Head1" runat="server">
<title>AJAX Example for comment</title>
<link href="Main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div id="page">
<div id="main">
<div id="shoutbox">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>Here's what everyone is saying:</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblShoutBox" runat="server"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="5000">
</asp:Timer>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddShout"
EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</p>
<p>
<asp:UpdatePanel ID="ShoutBoxPanel2" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p class="label">Name:</p>
<p class="entry">
<asp:TextBox ID="txtUserName" runat="server"
MaxLength="15" Width="100px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ErrorMessage="Name is required."
ControlToValidate="txtUserName" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<p class="label">Shout:</p>
<p class="entry">
<asp:TextBox ID="txtShout" runat="server"
MaxLength="255" Width="220px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server" ErrorMessage="Shout is required."
ControlToValidate="txtShout" Display="Dynamic"
CssClass="error">
</asp:RequiredFieldValidator>
</p>
<asp:Button ID="btnAddShout" runat="server" Text="Add Shout"
onclick="btnAddShout_Click" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
DynamicLayout="False">
<ProgressTemplate>
<img src="Images/spinner.gif" alt="Please Wait" />
Comment...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
</p>
</div>
</div>
</div>
</form>
</body>
</html>
And this is your C# Code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShoutItemList shoutBox;
if (Application["ShoutBox"] == null)
{
shoutBox = new ShoutItemList();
Application.Add("ShoutBox", shoutBox);
}
else
{
shoutBox = (ShoutItemList)Application["ShoutBox"];
lblShoutBox.Text = shoutBox.Display();
}
if (ScriptManager1.IsInAsyncPostBack != true)
txtUserName.Focus();
}
protected void btnAddShout_Click(object sender, EventArgs e)
{
ShoutItem shout = new ShoutItem();
shout.UserName = txtUserName.Text;
shout.Comment = txtShout.Text;
shout.Timestamp = DateTime.Now;
Application.Lock();
ShoutItemList shoutBox = (ShoutItemList)Application["ShoutBox"];
shoutBox.Add(shout);
Application.UnLock();
lblShoutBox.Text = shoutBox.Display();
txtShout.Text = "";
txtShout.Focus();
}
}
public class ShoutItem
{
public string UserName { get; set; }
public DateTime Timestamp { get; set; }
public string Comment { get; set; }
}
public class ShoutItemList
{
private List<ShoutItem> shoutList = new List<ShoutItem>();
private void Purge()
{
DateTime purgeTime = DateTime.Now;
purgeTime = purgeTime.AddMinutes(-3);
int i = 0;
while (i < shoutList.Count)
{
if (shoutList[i].Timestamp <= purgeTime) shoutList.RemoveAt(i);
else i += 1;
}
}
public void Add(ShoutItem shout)
{
Purge();
System.Threading.Thread.Sleep(2000);
shoutList.Insert(0, shout);
}
public string Display()
{
Purge();
StringBuilder shoutBoxText = new StringBuilder();
if (shoutList.Count > 0)
{
shoutBoxText.AppendLine("<dl>");
foreach (ShoutItem shout in shoutList)
{
shoutBoxText.Append("<dt>" + shout.UserName + " (");
shoutBoxText.Append(shout.Timestamp.ToShortTimeString() + ")</dt>");
shoutBoxText.AppendLine("<dd>" + shout.Comment + "</dd>");
}
shoutBoxText.AppendLine("</dl>");
}
return shoutBoxText.ToString();
}
}
This will allow you to insert whatever comment you want. You can modify this code to your own please....
Let me know if this is the answer you seek.
Use the button's OnClientClick, like this:
<asp:Button ID="Button1" runat="server" Text="Comment" OnClientClick="return javascriptFunction();" OnClick="Button1_Click"/>
then your javascript function would look like this
function javascriptFunction() {
//do something here
return false; //if you don't want the form to POST to the server, leave this as false, otherwise true will let it continue with the POST
}

Displaying sourcecode when clicking a button

First I have to let you know that i am a newbie in this area, learning from tutorials.
With that said I'm looking for a way to load sourcecode from the codebehind file into a textbox, when clicking a button. Same goes for the aspx file.
Im making this website, where i am going to show code examples from what im doing. So if I navigate to myweb.com/tutorial1done.aspx this page would show me the final result from the tutorial done. When i click the show source button it should make 2 textboxes visible, and add the codebehind to the first box, and the aspx source to the second box.
I don't know if it is possible, but I am hoping so.
This far i have this:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DateTimeOutput.aspx.cs" Inherits="WebApplication1.DateTimeOutput" %>
<!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 rel="stylesheet" href="../styles/codeformatter.css" />
</head>
<body>
<form id="form1" runat="server">
<customControls:Header runat="server" heading="Date and Time Output" />
<div>
<asp:Panel ID="Panel1" runat="server">
<asp:TextBox ID="outputText" runat="server" Height="175px" TextMode="MultiLine"
Width="400px"></asp:TextBox>
</asp:Panel>
</div>
<asp:Panel ID="Panel2" runat="server">
<asp:Button ID="runButton" runat="server" Text="Run Code"
onclick="runButton_Click" Width="95px" />
<asp:Button ID="clearButton" runat="server" Text="Clear Console"
onclick="clearButton_Click" Width="95px" />
<br />
<br />
<asp:Button ID="dt_showSource_btn" runat="server"
onclick="dt_showSource_btn_Click" Text="Show Source" />
</asp:Panel>
<asp:Label ID="dtLabel1" runat="server" Text="Code Behind:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtcb_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
<br />
<br />
<asp:Label ID="dtLabel2" runat="server" Text="ASPX:" Visible="False"></asp:Label>
<br />
<asp:TextBox ID="dtaspx_output" runat="server" Height="175px"
TextMode="MultiLine" Visible="False" Width="400px"></asp:TextBox>
</form>
</body>
</html>
And the Codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class DateTimeOutput : System.Web.UI.Page
{
protected void output(String value)
{
outputText.Text += value + Environment.NewLine;
}
protected void runButton_Click(object sender, EventArgs e)
{
DateTime dt = new DateTime();
output(dt.ToString());
DateTime nowDt = DateTime.Now;
output(nowDt.ToString());
}
protected void clearButton_Click(object sender, EventArgs e)
{
outputText.Text = "";
}
protected void dt_showSource_btn_Click(object sender, EventArgs e)
{
if (dtcb_output.Visible == false)
{
dtLabel1.Visible = true;
dtcb_output.Visible = true;
}
else
{
dtLabel1.Visible = false;
dtcb_output.Visible = false;
}
if (dtaspx_output.Visible == false)
{
dtLabel2.Visible = true;
dtaspx_output.Visible = true;
}
else
{
dtLabel2.Visible = false;
dtaspx_output.Visible = false;
}
}
}
}
For now source highlighting is not needed, unless its easy to do.
Thx in advance.
If you're refering to the actual code of your code behind file, you have a problem. As the file will be compiled and then be placed as intermediate code in a dynamic link library (.dll), you don't have access to the .aspx.cs file any more. The only way to go would be to include the code behind file with the deployd project and open it with a FileStream (or whatever) to read it and display it's content.

Categories

Resources