In this article, i am going to show how to validate two dates in asp.net using JavaScript. It also make sure that difference between two dates should not be more than n number of days. In my case, i specified 7 but you can specify it according to your need.
function ValidateDate() { var startDate = document.getElementById("<%=txtDatefrom.ClientID%>"); var endDate = document.getElementById("<%=txtDateTo.ClientID%>");//Get 1 day in milliseconds var oneDay = 1000 * 60 * 60 * 24; // to make sure end date is greater than or equal to start date if ((Date.parse(startDate.value) > Date.parse(endDate.value))) { $(endDate).css('border', '1px solid red'); return false; } else { // to make sure difference between two dates should not be more than 7 days if (Math.round((Date.parse(endDate.value) - Date.parse(startDate.value)) / oneDay) > 7) { $(endDate).css('border', '1px solid red'); return false; } $(endDate).css('border', '1px solid #d3cfc7'); return true; } }
C#, ASP.NET, ASP.NET MVC, OOPs, EWS Managed API, Web Application, Ms Sql Server, Javascript, JQUERY, CSS, LINQ, Entity Framework
Saturday, 17 January 2015
How to compare two dates in ASP.NET using JAVASCRIPT
Sunday, 9 November 2014
Validate File format and Size in ASP.NET using JAVASCRIPT
In this article, i am going to show how to valid file type and size of the file upload control in asp.net using JavaScript.
JavaScript Function
<script type="text/javascript">
// allowed file formats
var validFilesType = ["bmp", "gif", "png", "jpg", "jpeg"];
function ValidateFileTypeWithSize() {
var fluploadImage = document.getElementById("<%=fluploadImage.ClientID%>");
var lblMsg = document.getElementById("<%=lblMsg.ClientID%>");
lblMsg.style.color = "red";
lblMsg.innerHTML = '';
var path = fluploadImage.value;
// to get file extenstion like bmp, gif etc.
var extension = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesType.length; i++) {
if (extension == validFilesType[i]) {
isValidFile = true;
// mention maximum size
if (fluploadImage.files[0].size > 4194304) {
fluploadImage.value = ''; // to clear fileuploader content
lblMsg.innerHTML = "Each image file can't exceed 4 MB";
}
break;
}
}
// execute only in case of any file format which was not mentioned in 'validFilesType' variable
if (!isValidFile) {
fluploadImage.value = ''; // to clear fileuploader content
lblMsg.innerHTML = "File Not Valid. Please upload a File with" +
" extension:\n\n" + validFilesType.join(", ");
}
return isValidFile;
}
</script>
Controls
<asp:FileUpload ID="fluploadImage" onchange="ValidateFileTypeWithSize()" runat="server" />
<asp:Label ID="lblMsg" runat="server"></asp:Label>
Output
That’s it!!…..Happy Programming...
Saturday, 25 October 2014
Something about Empty String
In this article, i am going to explain meaning of an Empty String in int type column.
As we can see, implicit conversion of the empty string to a value of 0 happened here. These Issues sometimes can create problems for us. So from now, we have to care about Empty String more.
create table tblEmptyString (SrNo int null)
insert into tblEmptyString (SrNo) values (1)
insert into tblEmptyString (SrNo) values (2)
insert into tblEmptyString (SrNo) values ('')
insert into tblEmptyString (SrNo) values (null)
select * from tblEmptyString
Output
That’s it!!…..Happy Programming...
Saturday, 18 October 2014
CSS tooltip on hover
In this article, i am going to show how to apply custom styles on Tooltip.
In CSS, we have set the content attribute to content: attr(accesskey); this property will display the tooltip by using the accesskey attribute of the anchor tag. Whatever we pass in to the accesskey attribute of the anchor tag it will be displayed as a tooltip. Have something to add to this post? Share it in the comments.
Aspx Code
<table style="width: 300px;">
<tr>
<td>Username:
</td>
<td>
<a href="#" accesskey="Please enter your username" class="tooltipshow">
<input id="txtUsername" type="text" /></a>
</td>
</tr>
<tr>
<td>Password:
</td>
<td>
<a href="#" accesskey="Please enter your password" class="tooltipshow">
<input id="txtPassword" type="text" /></a>
</td>
</tr>
<tr>
<td></td>
<td>
<input id="btnSubmit" type="button" value="Login" />
</td>
</tr>
</table>
CSS Code
.tooltipshow {
display:inline;
position:relative;
text-decoration:none;
top:0;
left:10px;
}
.tooltipshow:hover:after {
background:rgba(0,0,0,.8);
border-radius:5px;
top:-5px;
color:#fff;
content:attr(accesskey);
left:160px;
position:absolute;
z-index:98;
width:150px;
padding:5px 15px;
}
.tooltipshow:hover:before {
border:solid;
bottom:20px;
content:"";
left:155px;
position:absolute;
z-index:99;
top:3px;
border-color:transparent #000;
border-width:6px 6px 6px 0;
}
In CSS, we have set the content attribute to content: attr(accesskey); this property will display the tooltip by using the accesskey attribute of the anchor tag. Whatever we pass in to the accesskey attribute of the anchor tag it will be displayed as a tooltip. Have something to add to this post? Share it in the comments.
Output
That’s it!!…..Happy Programming...
Saturday, 11 October 2014
Bind Category and Subcategory in asp.net
In this article, i am going to explain how to maintain Category and Subcategory hierarchy in asp.net.
Aspx Page
<form id="form1" runat="server">
<div>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
<ul>
<asp:Repeater ID="repCategory" runat="server" OnItemDataBound="repCategory_ItemDataBound">
<ItemTemplate>
<li>
<asp:Label Font-Size="Large" Font-Bold="true" ID="lblCategoryName" runat="server"
Text='<%# Eval("CategoryName") %>' />
</li>
<ul>
<asp:Repeater ID="repSubCategory" runat="server">
<ItemTemplate>
<li style="background-color:lightblue">
<asp:HyperLink ID="hlkSubCategory" runat="server" Text='<%# Eval("SubCategoryName")%>' />
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</form>
CS Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Category : System.Web.UI.Page
{
string strConnection = @"Data Source=AMREEK\SQLEXPRESS; uid=sa; pwd=12345;database=demo;";
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
try
{
SqlConnection myConnection = new SqlConnection(strConnection);
SqlCommand myCommand = new SqlCommand("[dbo].[GetCategoryWithSubCategory]", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
// Attach the relationship to the dataSet with relationship name, parent column, child column
ds.Relations.Add(new DataRelation("CategoriesRelation", ds.Tables[0].Columns["CategoryID"],
ds.Tables[1].Columns["CategoryID"]));
repCategory.DataSource = ds.Tables[0];
repCategory.DataBind();
}
catch(Exception ex)
{ Response.Write(ex.Message); }
}
protected void repCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = e.Item.DataItem as DataRowView;
Repeater innerRep = e.Item.FindControl("repSubCategory") as Repeater;
innerRep.DataSource = drv.CreateChildView("CategoriesRelation");
innerRep.DataBind();
}
}
}
SQL Query
-- category table --
create table category
(
categoryId int identity primary key not null,
categoryName nvarchar(100) not null
)
insert category values ('a')
insert category values ('b')
insert category values ('c')
select * from category
-- sub category table --
create table subcategory
(
categoryId int not null FOREIGN KEY REFERENCES category(categoryId),
subcategoryId int identity not null,
subcategoryName nvarchar(100) not null,
)
insert subcategory values (1,'one')
insert subcategory values (1,'two')
insert subcategory values (1,'three')
insert subcategory values (2,'one')
insert subcategory values (2,'two')
insert subcategory values (3,'one')
insert subcategory values (3,'two')
insert subcategory values (3,'three')
insert subcategory values (3,'four')
select * from subcategory
-- procedure to select both tables data --
Go
Create PROCEDURE [dbo].[GetCategoryWithSubCategory]
AS
-- only those categories selected whose sub-categories exist
SELECT * FROM category WHERE CategoryID IN
( SELECT CategoryID FROM subcategory )
-- select all records from subcategories, here p just used as alias
SELECT p.subcategoryId , p.SubCategoryName ,p.CategoryID FROM subcategory p
Go
Output
That’s it!!…..Happy Programming...
Friday, 3 October 2014
How to Add Dynamic Rows in Gridview in ASP.NET
In this article, i am going to show how to add dynamic rows in gridview control..
That’s it!!…..Happy Programming...
aspx page
<asp:GridView ID="gvRecords" runat="server" OnRowCommand="gvRecords_RowCommand" DataKeyNames="SrNo" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Sr No.">
<ItemTemplate>
<asp:TextBox ID="txtSrNo" runat="server" Text='<%# Eval("SrNo") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Salary">
<ItemTemplate>
<asp:TextBox ID="txtAmount" runat="server" Text='<%# Eval("Salary") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="cmd_delete" Text="Delete" />
</Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />
cs page
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 dynamicgridview : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvRecords.DataSource = GetTableWithInitialData(); // get initial data
gvRecords.DataBind();
}
}
public DataTable GetTableWithInitialData()
{
DataTable table = new DataTable();
table.Columns.Add("SrNo", typeof(string));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(double));
table.Rows.Add(1, "Manpreet", 25000);
table.Rows.Add(2, "Gurpreet", 20000);
table.Rows.Add(3, "Prabhjot", 33000);
SaveGridInViewstate(table);
return table;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
DataTable dt = GetTableWithNoData(); // get table structure by calling the specified function
DataRow dr;
foreach (GridViewRow gvr in gvRecords.Rows)
{
dr = dt.NewRow();
TextBox txtSrNo = gvr.FindControl("txtSrNo") as TextBox;
TextBox txtName = gvr.FindControl("txtName") as TextBox;
TextBox txtAmount = gvr.FindControl("txtAmount") as TextBox;
dr[0] = txtSrNo.Text;
dr[1] = txtName.Text;
if (txtAmount.Text == string.Empty)
{
dr[2] = DBNull.Value;
}
else
{
dr[2] = txtAmount.Text;
}
dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
}
dr = dt.NewRow(); // add new empty row
dt.Rows.Add(dr);
gvRecords.DataSource = dt; // bind newly created datatable to grid
gvRecords.DataBind();
SaveGridInViewstate(dt);
}
public DataTable GetTableWithNoData() // returns only table structure
{
DataTable table = new DataTable();
table.Columns.Add("SrNo", typeof(string));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(double));
return table;
}
// save datatable into viewstate which would be useful for deletion
public void SaveGridInViewstate(DataTable dt)
{
ViewState["gvRecords"] = dt;
}
protected void gvRecords_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmd_delete")
{
int index = Convert.ToInt32(e.CommandArgument);
if (ViewState["gvRecords"] != null)
{
dt = ViewState["gvRecords"] as DataTable;
DataRow row = dt.Rows[index];
dt.Rows.Remove(row);
gvRecords.DataSource = dt; // bind newly created datatable to grid
gvRecords.DataBind();
}
}
}
}
Output
That’s it!!…..Happy Programming...
Subscribe to:
Posts (Atom)