Making a small Popup picture on mouse over event




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MouseOverGrid.aspx.cs" Inherits="MouseOverGrid" %>

<!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>Untitled Page</title>

<script type="text/javascript">
function get_(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="block";
}
function get_1(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="none";
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Details" onmouseover="get_(this);"
onmouseout="get_1(this);" />
<div id="lnk1" runat="server" style="display: none; position: absolute; background-color: #FEFFB3;
width: 150px"
>
<p>
<strong>Image Name</strong></p>
<p>
<img src='<%#Eval("ImagePath")%>' runat="Server" id="A" /></p>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>








using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MouseOverGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

}
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Movie");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/sa2.jpeg";
dt.Rows.Add(dr);
}
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/pdf-icon.jpg";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

Enum With String Values In C#




In this post i will show how to assign string value to enum(In C# you cannot have an enum that has string values)
Step1
First I created the new custom attribute class, the source is below:
Step2
Then I created a new which I will use to get the string value for an enums value:



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Reflection;
public class StringValueAttribute : Attribute
{
public string StringValue;

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}
public static class Util
{
public static string GetStringValue(Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}

}


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EnumToString.aspx.cs" Inherits="EnumToString" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>





using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class EnumToString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string val = Util.GetStringValue(Test.Something);
Response.Write(val);
}

}

public enum Test : int
{
[StringValue("Value1")]
Foo = 1,
[StringValue("Value2")]
Something = 2
}

using arrayList as DataSource for Gridview



Let us suppose that you have four controls (TextBox ,DropDownList ,ListBox ) and your requirement is that when the user enters texts or make a selection all these items/values gets stored inside an ArrayList and then this Array List is used as the Data Source for a Gridview control.




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicData.aspx.cs" Inherits="DynamicData" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" /><br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList><br />
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList><br />
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:ListBox><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Txt1" HeaderText="TextBox1" />
<asp:BoundField DataField="DDL1" HeaderText="DropDownList1" />
<asp:BoundField DataField="DDL2" HeaderText="DropDownList2" />
<asp:BoundField DataField="Lst1" HeaderText="ListBox1" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

public partial class DynamicData : System.Web.UI.Page
{
private List<Row> Data
{
get
{
if (this.ViewState["Data"] == null)
{
this.ViewState["Data"] = new List<Row>();
}

return this.ViewState["Data"] as List<Row>;
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetData();
}
}

private void GetData()
{
GridView1.DataSource = this.Data;
GridView1.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
Row obj = new Row();
obj.Txt1 = TextBox1.Text;
obj.DDL1 = DropDownList1.SelectedValue;
obj.DDL2 = DropDownList2.SelectedValue;
obj.Lst1 = ListBox1.SelectedValue;
this.Data.Add(obj);

this.GetData();
}



}
[Serializable()]
public class Row
{

private string _txt1;
private string _ddl1;
private string _ddl2;
private string _Lst1;

public string Lst1
{
get { return _Lst1; }
set { _Lst1 = value; }
}


public string DDL2
{
get { return _ddl2; }
set { _ddl2 = value; }
}


public string DDL1
{
get { return _ddl1; }
set { _ddl1 = value; }
}

public string Txt1
{
get { return _txt1; }
set { _txt1 = value; }
}

}

Tips

how to resolve the error

One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. for more details check out this link

Binding a Listcontrol(Dropdownlist) to Enumeration Values




<%@ Page Language="C#" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
public void AddEnumToList(Type GetSystemType, ListControl List)
{
// Populates the specified list with the
// names and values of the passed system type
string[] strNames;
System.Array arrValues;
int intCount;
strNames = Enum.GetNames(GetSystemType);
arrValues = Enum.GetValues(GetSystemType);
List.Items.Clear();
for (intCount = strNames.GetLowerBound(0); intCount < strNames.GetUpperBound(0); intCount++)
{
List.Items.Add(new ListItem(strNames[intCount].ToString(), arrValues.GetValue(intCount).ToString()));
}
}

public enum Test
{

Jan,
Feb,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December

}


protected void Page_Load(object sender, EventArgs e)
{
Test a = new Test();
AddEnumToList(typeof(Test), DropDownList1);
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></div>
</form>
</body>
</html>

The .NET Replacement for App.Path

A lot of confusion surrounds how to find out the startup path of your application —the .NET equivalent of the App.Path property we had in Visual Basic 6. I’ve personally written my own elongated routines, when in fact the solution is incredibly simple.

If you want to find out the application path of your Windows application, just reference the StartupPath property of the Application object, as so:

Dim strPath As String = Application.StartupPath 

Note that the returned path doesn’t include a trailing slash.

If you’re developing a class library or similar project, however, you might stumble upon a slight problem. You see, not all projects support the Application object. In these cases, you can use the System.Reflection class to analyze the executing assembly and return its location. A little like this:

Dim strPath As String = System.Reflection.Assembly.GetExecutingAssembly().Location 

A bit more in depth, but still pretty darn simple

How To Post Data From ASP.net To Another URL





using System;
using System.Net;
using System.Web;
using System.Collections.Specialized;


public class RemotePost
{
NameValueCollection Inputs = new NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("<html><head>");
HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
int i = 0;
while (i < Inputs.Keys.Count)
{
HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i],Inputs.Keys[i]));
i += 1;
}
HttpContext.Current.Response.Write("</form>");
HttpContext.Current.Response.Write("</body></html>");
HttpContext.Current.Response.End();
}
}


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
RemotePost obj = new RemotePost();
obj.Url = "http://localhost/Project/Default.aspx";
obj.Method = "Get";
obj.Add("test", "test");
obj.Post();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Post Data To Another Application" /></div>
</form>
</body>
</html>


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["test"] != null)
{
Response.Write(Request.Form["test"].ToString());

}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

How To Convert HTML to Text, Easily



Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy.

It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:



<%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs"
Inherits="StripTag" %>


<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Height="172px" Width="363px" TextMode="MultiLine"></asp:TextBox></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class StripTag : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
public string StripTags(string HTML)
{
// Removes tags from passed HTML
return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "");
}


protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = StripTags(TextBox1.Text);

}
}

How to View one record per page in ASP.NET?






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SinglePage.aspx.cs" Inherits="SinglePage" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:TextBox ID="txtProductName" runat="server" OnDataBinding="txtDataBind"></asp:TextBox>
<asp:TextBox ID="txtProductid" runat="server"></asp:TextBox>
<asp:Button ID="btnPrevious" runat="server" Text="Previous" OnClick="PrevBtn"></asp:Button>
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="NextBtn"></asp:Button>
</div>
</form>
</body>
</html>









using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class SinglePage : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
dt = GetDataTable() as DataTable;

if (!Page.IsPostBack)
{
ViewState["CurrentPos"] = 0;
this.DataBind();
}
}
protected void PrevBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
if (CurrentPos > 0)
{
CurrentPos -= 1;
}
ViewState["CurrentPos"] = CurrentPos;
this.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

protected void NextBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
CurrentPos += 1;
if (CurrentPos > dt.Rows.Count)
{
CurrentPos -= 1;
}
ViewState["CurrentPos"] = CurrentPos;
this.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

protected void txtDataBind(Object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
ViewState["CurrentPos"] = CurrentPos;
txtProductid.Text = dt.Rows[CurrentPos]["productid"].ToString();
txtProductName.Text = dt.Rows[CurrentPos]["productname"].ToString();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Product");
dt.Columns.Add("ProductID", Type.GetType("System.Int32"));
dt.Columns.Add("ProductName", Type.GetType("System.String"));

//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ProductID"];
dt.PrimaryKey = pk;
dt.Columns["ProductID"].AutoIncrement = true;
dt.Columns["ProductID"].AutoIncrementSeed = 1;
dt.Columns["ProductID"].ReadOnly = true;

//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["ProductName"] = "Riss";

dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["ProductName"] = "Product";

dt.Rows.Add(dr);

}
}

return dt;
}
}

Filling typed dataset programmatically

Filling a typed dataset works just like filling an untyped dataset. You create a data adapter, assign the SelectCommand, and call Fill(). The only real trick is to get the table and field names right. A DataAdapeter will generate table names for each distinct result set generated by the SelectCommand. The names will be "Table", "Table1", "Table2", etc. If you call the overloaded Fill() method which takes a table name parameter, the generated names will follow the same pattern, except your table name will be used instead of "Table". Once the data adapter has generated the table names, it will look for matching table names in your data set. The data is then mapped to the matching column names in the matching tables. As long as the SelectCommand returns the proper column names, the data will populate as you would expect. Some things to beware of: * You will *not* get errors if the table or column names are wrong. If the Data Adapter can't find a given table, it would normally add a new table to your dataset. For typed data sets, things are slightly different. You won't get an exception in this case, but you also wont' get your data. This includes both misnamed tables *and* misnamed columns -- the data is simply discarded if it can't be fit into your schema. * If your SelectCommand returns multiple result sets, you will almost certainly need to map the resulting table names to those in your dataset. The table names need to be mapped in the order they are returned by the SelectCommand, and the code looks something like this (assume the dataset has three tables: MyTable, MyOtherTable, MyThirdTable):
SqlCommand cmd = new SqlCommand("multi_recordset_proc", new SqlConnection("your con. string"));

          cmd.CommandType = CommandType.StoredProcedure;

          SqlDataAdapter da = new SqlDataAdapter(cmd);
          da.TableMappings("MyTable1", "MyOtherTable");
          da.TableMappings("MyTable2", "MyThirdTable");
          da.Fill(dataset, "MyTable");
* If you have relationships in your dataset, they will be enforced during the Fill. I beleive this is done on a per-table basis, that is, the contraints for a given table are disabled, data is populated, and the constraints are enabled. If you populate a table before populating parent tables, you will generate an error. You can get around this problem by being careful of the order you populate tables. Alternatively, you can do:
ds.EnforceConstraints = false;
           da.Fill(ds, "Table");
           ds.EnforceConstraints = true;

How To Clear Browser Session In Asp.net

In this post i will show how to clear Browser history in asp.net.just write down following code in Logout button.
protected void LogOut()
   {
       Session.Abandon();
       string nextpage = "Logoutt.aspx";
       Response.Write("<script language=javascript>");

       Response.Write("{");
       Response.Write(" var Backlen=history.length;");

       Response.Write(" history.go(-Backlen);");
       Response.Write(" window.location.href='" + nextpage + "'; ");

       Response.Write("}");
       Response.Write("</script>");

   }

How to easily insert row in GridView with SqlDataSource?

Asp.Net 2.0 GridView control is very powerful control. Developers at Microsoft really did a great job when designing it. Its like Swiss Army knife for selecting, editing, sorting, paging and displaying data. Combined with various DataSource controls (ObjectDataSource, SqlDataSource) it helps you execute most of your Read, Update and Delete operations without writing a single line of code. Off course, nothing is perfect. For example, creating new data is is one common task that is not so simple to accomplish with GridView. Since there is InsertCommand property in DataSource controls that we can set to insert data, there is no reason not to use it with GridView to insert new data, just like we use DeleteCommand to delete data. For some strange reason there is no built-in way to do this, but there are always workarounds check out this link

Passing Date from Calendar Pop-Up to Parent Window





This section will help us building a simple DatePicker control using Calendar control and Javascript. Create two aspx pages, ParentPage.aspx and Calendar.aspx. Calendar.aspx will contain a Calendar control and it should be opened as a popup window. When the user selects a date in the Calendar popup it will populate the date selected into a textbox in the ParentPage.aspx page.


ParentPage.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ParentPage.aspx.cs" Inherits="ParentPage" %>

<!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>Untitled Page</title>

<script type="text/javascript">
function PopupPicker(ctl)
{
var PopupWindow=null;
PopupWindow=window.open('Calender.aspx?ctl='+ctl,'','width=250,height=250');
PopupWindow.focus();
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<input id="Button2" type="button" value="Click" onclick="PopupPicker('txtDate');" />
</div>
</form>
</body>
</html>



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Calender.aspx.cs" Inherits="Calender" %>

<!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>Untitled Page</title>

<script type="text/javascript">
function SetDate(dateValue,ctl)

{

thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue;
self.close();
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Cal1" runat="Server" OnDayRender="Cal1_DayRender"></asp:Calendar>
</div>
</form>
</body>
</html>




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Calender : System.Web.UI.Page
{
string ctrl;
protected void Page_Load(object sender, EventArgs e)
{
ctrl = Request.QueryString["ctl"].ToString();
}

protected void Cal1_DayRender(object sender, DayRenderEventArgs e)
{

HyperLink hpl = new HyperLink();
hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text;
hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() + "','" + ctrl + "');";
e.Cell.Controls.Clear();
e.Cell.Controls.Add(hpl);

}
}
By default, the days in calendar control is rendered as links and generate a postback when it is clicked. Instead of postback, we will call our custom SetDate() JavaScript function by changing the cell of the Calendar control to Hyperlink control and attaching the SetDate() JavaScript function to the hyperlink in clnDatePicker_DayRender event.

Working With PopUp In ASP.net



Whenever we build any web applications it can have requirements to work with popup windows. For example: To pick a date for a date field in an aspx page, we can place a calendar control on a popup so that user can select a date from the calendar instead of typing himself, a simple date picker control. This article will help you understand some of tasks that we more often do with popup windows.

Refreshing a parent page from a popup ASP.Net page

There are situations where we will be required to populate the information’s entered on the popups to the parent page and refresh the parent page so that it can be accessed in the server side. The below example will help us in achieving it.

The below example will populate the entered name in the child.aspx(popup) to the parent(Parent.aspx) and submit the page to the server.
Parent.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Parent.aspx.cs" Inherits="Parent" %>

<!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>
<title>Untitled Page</title>

<script language="javascript">

function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

}

</script>

</head>
<body>
<form runat="Server">
<div>
<asp:textbox id="txtName" runat="server"></asp:textbox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Value" />
<input type="button" id="Button1" value="Enter Name" onclick="OpenWindow('Child.aspx')" />
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}

}
protected void Button2_Click(object sender, EventArgs e)
{
if (txtName.Text != "")

Response.Write(txtName.Text);

}
}

child.aspx



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Child.aspx.cs" Inherits="Child" %>

<!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>Untitled Page</title>

<script language="javascript">

function SubmitToParent()

{

window.opener.document.forms[0].txtName.value = document.getElementById('txtChildName').value;

window.opener.document.forms[0].submit();

self.close();

}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtChildName" runat="server"></asp:TextBox>
<input type="button" id="Button1" value="Submit to Parent" onclick="SubmitToParent()" />
</div>
</form>
</body>
</html>
Window.Open Clears Parent page and writes [Object]



Sometimes we will have requirements to open an asp.net page as a popup when we click a hyperlink. Consider the below code,



<a href="javascript:window.open('http:/google.com')"> google</a>



The above code will clear the existing content on the page and will output only [Object]. This behaviour is because the actual return value of Window.Open function is the window object itself.

To prevent the above behaviour and have the parent page without clearing its existing content we need to change the above code similar to below,



<a href="javascript:void(window.open('http:/google.com'))"> google</a>

or

<a href="#" onclick="javascript:window.open('http:/google.com'); return false;"> google</a>
Opening ASP.Net Popup window in specific location of the screen




Opening ASP.Net Popup window in specific location of the screen



Sometimes we would like to open our popup window on specific location on our screen. This can be done by MoveTo() method of the window object.



function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

testwindow.moveTo(100,0);

}

The null coalescing operator: ??

This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows
string newValue = someValue ?? "default";

The first operand someValue must be a nullable type. The above code will set the value of newValue to someValue unless it's null, then it'll set it to "default".

You could also use this inline:

Console.WriteLine("The value is " + (someValue ?? "null"));

another use
return (bool)(ViewState["IsPaged"] ?? true);

Programmatically adding LINKs to HTML HEADER in Code Behind

In this example I am adding a link to the html header pointing to an rss feed.
HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "application/rss+xml");
link.Attributes.Add("rel", "alternate");
link.Attributes.Add("href", Page.ResolveClientUrl("~/rss/LatestArticles/"));
this.Header.Controls.Add(link);

How To Restrict the number of rows in a dataview when binding to a GridView


In this post i will show how to restrict the number of items bound to an asp:GridView. Basically I never wanted more than 10 items to be displayed.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RestrictNumRows.aspx.cs"
Inherits="RestrictNumRows" %>


<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server">
</asp:GridView>
</div>
</form>
</body>
</html>




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class RestrictNumRows : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

FilterRows obj = new FilterRows(GetDataSet().DefaultView,2);
GridView1.DataSource = obj;
GridView1.DataBind();
}

}
public class FilterRows : IEnumerable
{
DataView dataView;
private int rowsToShow;

public FilterRows(DataView dataView, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.dataView = dataView;
}

public IEnumerator GetEnumerator()
{
return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow);
}


internal class PageOfData : IEnumerator
{
private IEnumerator e;
private int cnt = 0;
private int rowsToShow;

internal PageOfData(IEnumerator e, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.e = e;
}

public object Current
{
get { return e.Current; }
}

public bool MoveNext()
{
// If we've hit out limit return false
if (cnt >= rowsToShow)
return false;

// Track the current row
cnt++;

return e.MoveNext();
}

public void Reset()
{
e.Reset();
cnt = 0;
}
}
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 1; i <= 20; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}

}