May 27, 2010

How to check for session timeout (asp.net, c#)

For checking Session Time Out use following code:
if (Context.Session != null)

Page.Previos is null error (ASP.NET, C#)

Use Page.Previous with Server.Transfer for perfect results. It works perfectly with “Transfer of the page”

With response.redirect it is not working properly – sometimes returning null value.

Could not load type error in asp.net 2.0

Change “CodeBehind” file to “CodeFile” in aspx.cs file

How to put value in asp.net textbox placed in content page using JavaScript? (ASP.NET, C#, JavaScript)

When using master page and content page in asp.net, original ids of the controls (used in aspx page) are changed during execution of the page, because the whole page will be served as HTML page to the viewer. The ids are prefixed with ContentPlaceHolder ID and some other information.

So what we can do is, we can match the original ids of the control, within this new ids generated by asp.net server to find that control.

Once we get the control, we can do our normal java scripting.

Example : A search page opens a new window upon clicking on "search" button. This new window passes some value to search page's textbox and closes itself upon clicking on its "Click" button. Both pages uses a master page.

For example I have a master page and 2 content pages(page1.aspx, page2.aspx).

Page1.aspx have following code:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script type="text/javascript">
function OpenPopup()
{
    window.open("Default2.aspx","List","scrollbars=yes,resizable=yes,width=550,height=480");
    return false;
}
</script>

<asp:TextBox ID="tbx_Name" runat="server"></asp:TextBox>
<asp:Button ID="bt_search" runat="server" Text="search" />

</asp:Content>

Page1.aspx.cs page have following code:

protected void Page_Load(object sender, EventArgs e)
{
     bt_search.Attributes.Add("onclick", "javascript:return OpenPopup()");
}

Page2.aspx have following code:

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript">
function GetUserValue(val)
{
       frm=window.opener.document.forms[0];
       for (var i=0;i<frm.length;i++)
      {
            str=frm.elements[i].id;
            if (str.search("tbx_Name")>=0)
               { frm.elements[i].value="testing...";
               }
        }
      window.close();
}
</script>

<asp:Button ID="bt_UserName" runat="server" Text="Click" OnClick="bt_Click" />
<asp:Button ID="bt_Close" runat="server" Text="Close" />

</asp:Content>

Page2.aspx.cs page have following code:

protected void Page_Load(object sender, EventArgs e)
{
      bt_UserName.Attributes.Add("onclick", "javascript:GetUserValue('" + "Tim Johnson" + "')")
}

protected void bt_Click(object sender, EventArgs e)
{
      if (!Page.IsClientScriptBlockRegistered("ClosePopUp")) 
      {
              RegisterStartupScript("ClosePopUp", "<script language=\"javascript\">function CloseMe()      {window.close();window.history.back(); };</script>");
      }

      bt_Close.Attributes.Add("onclick", "ClosePopUp()");
}

Connection String - Adding connection string to Web.config file and accessin it (ASP.NET, C#)

Web.config File:

We can add conncetion string in web.config file for security reasons, in the following way:

<configuration>

<appSettings>

<add key="ConnectString" value="Server=servername;Database=databasename;uid=yourUserId;pwd=yourPassword"/>

Default.aspx.cs page:

Getting Connection String from web.config in c# program )(For example, Default.aspx.cs page_load event)

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectString Name"].ConnectionString);

May 20, 2010

How to display an error message of a vaildation control all the time?

To display an error message of validation control all the time, set that error message in the "Text" property of validation control.

Merging three table fields using DataBinder.Eval to display in a label control (ASP.NET, C#)

<asp:Label ID="lbl_Address" runat="server"  Text=’<%# DataBinder.Eval(Container.DataItem,"Location")+ ", " +DataBinder.Eval(Container.DataItem,"City") +", " +DataBinder.Eval(Container.DataItem,"State")%>’ ></asp:Label>

May 19, 2010

Regular Expression for AlphaNumeric Characters only

Regular Expression for AlphaNumeric Characters only :

^[0-9a-zA-Z\s]+$

It only allows 0-9,a-z, A-Z, $

Compare NULL values in SQL Query

You can compare NULL values using "IS NULL" after the field name of a table.

SELECT  id, name, city, zip  FROM  tableStudent  WHERE city IS NULL

Creating Regular Expression for Numeric Values and using it on a TextBox control in C#

//Creating regular expression for numeric values
Regex rxNum = new Regex(@"^[0-9\s]+$");

//using regular expression on  a TextBox Control in C#
if (!rxNum.IsMatch(textbox1.Text))
          Response.write("Textbox1 has Numeric value");

Change CSS of a ASP.NET control at runtime. (C#)

Let's add background color and width  to a Label control at runtime.
(Runtime means on button click event or something like that).

Label1.Attributes.CssStyle.Add("background-color", "#007700");
Label1.Attributes.CssStyle.Add("width", "320px");

Set a field of table to do auto entry as the current date when Inserting a new record in Micrososft SQL Server 2005

There are 2 simple ways to do it:

Method 1:
Complete the following steps and you are done:
  1. Right click on the name of table
  2. select design
  3. click on field where you want to create auto entry of current date
  4. now look in the “Column Properties” window
  5. Under the General group there is property called “Default value or Bindind”
  6. in that type in “(getdate())” and save.
Method 2:
You can use getdate() function in the insert query too.

How to get current user's name? (ASP.NET, C#)

You can get current logged in user's name in a label control as follows:

Label1.Text = User.Identity.Name.ToString();