Thursday, 18 December 2014

Call javascript function from code behind in C#

Call javascript function from code behind in C#


Suppose you want to call javascript function ParentRefresh() from code behind in C#.

<script type="text/javascript">
function ParentRefresh()
{
   // javascript code
}
</script>

protected void Save_Click(object sender, EventArgs e)
    {
// your save code
ScriptManager.RegisterStartupScript(this, GetType(), "message", "ParentRefresh();", true);
}

Access a parent element (Button) from iframe using c#

Access parent element (Button) from iframe using c#


Suppose you have 2 pages:
1. Parent Page: On which there is a iframe. as Parent.aspx
2. Loaded page: inside the iframe where Child.aspx is loaded

You want if you save some thing on Child.aspx (Loaded page), the grid on Parent page (Parent.aspx) will automatically refresh.  

So you make a hidden button on the Parent page (Parent.aspx)

<div style="display:none">
    <asp:Button ID="Done" runat="server" ClientIDMode="Static" OnClick="Done_Click" />
</div>

protected void Done_Click(object sender, EventArgs e)
    {
        // Refresh Grid
    }

Note that the ClientIDMode="Static" because from the other page you can not know what is the rendered id, so keep it static. If you do not use dot net 4 that have the static id, then you need to also use javascript to send the rendered id to the page, or some other way to 
locate the button.

Call a javascript function on Child.aspx (Loaded Page)

<script type="text/javascript">
function ParentRefresh()
{
   window.parent.document.getElementById('Done').click();
}
</script>

protected void Save_Click(object sender, EventArgs e)
    {
// your save code
ScriptManager.RegisterStartupScript(this, GetType(), "message", "ParentRefresh();", true);
}

Wednesday, 10 December 2014

Regular Expression for Date Format (dd/mm/yyyy) and (mm/yyyy)

Regular Expression for Date Format (dd/mm/yyyy):

(^(((0[1-9]|[12][0-8])[\/](0[1-9]|1[012]))|((29|30|31)[\/](0[13578]|1[02]))|((29|30)[\/](0[4,6,9]|11)))[\/](19|[2-9][0-9])\d\d$)|(^29[\/]02[\/](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)

Regular Expression for Date Format (mm/yyyy):

^((((((0[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$

Add a RequiredFieldValidator to DropDownList control

Add a RequiredFieldValidator to DropDownList control

ddl1.Items.Insert(0, "Please select");

<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" 

InitialValue="Please select" ErrorMessage="Please select something" />

Friday, 5 December 2014

If a folder does not exist, create it in C#

If a folder does not exist, create it in C#


string subPath ="ImagesPath"; // your code goes here

bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));

if(!exists)
    System.IO.Directory.CreateDirectory(Server.MapPath(subPath));