Archive

Archive for August, 2009

Disable a Button When Clicked once on an ASP.NET Page Containing Validation Controls

August 31, 2009 Leave a comment

Hi

try this example to Disable a Button When Clicked once on an ASP.NET Page Containing Validation Controls

<asp:Button ID="LoginButton" runat="server" Text="Login" OnClientClick="DisableButton(this)" />
<span id="loading" style="display: none;">Logging in...</span>

<script language="javascript" type="text/javascript">
function DisableButton(button)
{
    Page_ClientValidate();
    if (Page_IsValid)
    {
        button.style.display = 'none';
        document.getElementById('loading').style.display = 'inline';
    }
}
</script>

 Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, Javascript

Disable browser back button functionality using javascript in ASP.NET

August 26, 2009 Leave a comment

Hi

try this example :-

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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 disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
window.onunload=function(){null};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
This is First page <br />
<br />
Go to Second page
<br />
<br />
<asp:LinkButton ID="LinkButton1" runat="server"
PostBackUrl="~/Default2.aspx">Go to Second Page
</asp:LinkButton></div>
</form>
</body>
</html>

If you want to disable back button using C# code, than you need to write this code either in Page_load event or in Page_Init event

In other words we need to disable browser caching by writing this line of code

protected void Page_Init(object Sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}

Hope this helps

Good Luck

Categories: ASP.Net

Create RSS Feed using Linq

August 16, 2009 Leave a comment

Hi

try this example to create Rss Feed using linq :-

1) create new website using VS 2008

2) In this example i use Northwind database

3) Add new Data Context Class called “Northwind.dbml” and add Employee table in it

4) Add new web page and in code behind add the following code

protected void Page_Load(object sender, EventArgs e)
    {
        NorthwindDataContext context = new NorthwindDataContext();
        Response.Clear();
        Response.ContentType = "text/xml";
        XDocument document = new XDocument(
            new XDeclaration("1.0", "utf-8", null),
            new XElement("rss",
                new XElement("channel",
                    new XElement("title", "Employees of Northwind Traders Inc."),
                    new XElement("link", "http://www.yoursite.com"),
                    new XElement("description", "Employees of Northwind Traders Inc. ordered by last name."),
                    from emp in context.Employees
                    orderby emp.LastName
                    select new XElement("item",
                        new XElement("title", emp.LastName + ", " + emp.FirstName),
                        new XElement("description", emp.Notes),
                        new XElement("link", "http://www.yoursite.com/Details.aspx?id=" + emp.EmployeeID))
                        ),
                        new XAttribute("version", "2.0")));
        document.Save(Response.Output);
        Response.End();
    }

Hope this helps

Good Luck

Categories: Linq

Convert a DataReader to DataTable

August 16, 2009 Leave a comment

Hi

try this example to Convert a DataReader to DataTable using Northwind Database:

private void ConvertDateReadertoTableUsingLoad()
    {
        SqlConnection conn = null;
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;
            conn = new SqlConnection(connString);
            string query = "SELECT * FROM Customers";
            SqlCommand cmd = new SqlCommand(query, conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            DataTable dt = new DataTable();
            dt.Load(dr);
            GridView1.DataSource = dt;
            GridView1.DataBind();
           
        }
        catch (SqlException ex)
        {
            // handle error
        }
        catch (Exception ex)
        {
            // handle error
        }
        finally
        {
            conn.Close();
        }
    }

private void ConvertDataReaderToTableManually()
    {
        SqlConnection conn = null;
        try
        {
            string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;
            conn = new SqlConnection(connString);
            string query = "SELECT * FROM Customers";
            SqlCommand cmd = new SqlCommand(query, conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            DataTable dtSchema = dr.GetSchemaTable();
            DataTable dt = new DataTable();
            // You can also use an ArrayList instead of List<>
            List<DataColumn> listCols = new List<DataColumn>();
           
            if (dtSchema != null)
            {
                foreach (DataRow drow in dtSchema.Rows)
                {
                    string columnName = System.Convert.ToString(drow["ColumnName"]);
                    DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));
                    column.Unique = (bool)drow["IsUnique"];
                    column.AllowDBNull = (bool)drow["AllowDBNull"];
                    column.AutoIncrement = (bool)drow["IsAutoIncrement"];
                    listCols.Add(column);
                    dt.Columns.Add(column);
                }
            }
 
            // Read rows from DataReader and populate the DataTable
            while (dr.Read())
            {
                DataRow dataRow = dt.NewRow();
                for (int i = 0; i < listCols.Count; i++)
                {
                    dataRow[((DataColumn)listCols[i])] = dr[i];
                }
                dt.Rows.Add(dataRow);
            }
            GridView2.DataSource = dt;
            GridView2.DataBind();
        }
        catch (SqlException ex)
        {
            // handle error
        }
        catch (Exception ex)
        {
            // handle error
        }
        finally
        {
            conn.Close();
        }

   }

 Hope this helps

Good Luck

Categories: ASP.Net

Show Dynamic DIV as Tooltip

August 16, 2009 Leave a comment

Hi

try this example :-

JAVASCRIPT CODE

function ShowDiv(divid,iframe, state)
{
 var DivRef = document.getElementById(divid);
 var IfrRef = document.getElementById(iframe);
 if(state)
 {
  DivRef.style.display = "block";
  IfrRef.style.width = DivRef.offsetWidth;
  IfrRef.style.height = DivRef.offsetHeight;
  IfrRef.style.top = DivRef.style.top;
  IfrRef.style.left = DivRef.style.left;
  IfrRef.style.zIndex = DivRef.style.zIndex - 1;
  IfrRef.style.display = "block";
 }
 else
 {
  DivRef.style.display = "none";
  IfrRef.style.display = "none";
 }
}

<a href="#" onclick="ShowDiv('div','iframe', true); return false;">
<img src="image.gif" border="0" style="margin: 0px;" /></a>
<div id="div">div message</div>
<iframe id="iframe" scrolling="no" frameborder="0"></iframe>

 Hope this helps

Good Luck

Categories: ASP.Net, Javascript

LINQ to XML to Add and Read Data from XML File

August 15, 2009 Leave a comment

Hi

try this example to use LINQ to XML to Add  and Read Data from XML File

1) Open VS 2008 and create new website

2) Add new XML file  called :- Pepole.xml

<?xml version="1.0" encoding="utf-8"?>
<Persons>
  <Person>
    <Name>Yasser</Name>
    <City>Cairo</City>
    <Age>25</Age>
  </Person>
</Persons>

3) Add new web page :-

<div>
    <strong>Add to XML</strong><br />
 Name:<br />
 <asp:TextBox ID="txtName" runat="server" /><br />
 City:<br />
 <asp:TextBox ID="txtCity" runat="server" /><br />
 Age:<br />
 <asp:TextBox ID="txtAge" runat="server" /><br />
 <asp:Button ID="butAdd" runat="server" Text="Add" onclick="butAdd_Click" /><br />
 <asp:Label ID="lblStatus" runat="server" />
 <br /><br />
 <strong>Read XML:</strong><br />
 <asp:Button ID="butRead" runat="server" Text="Read" onclick="butRead_Click" /><br />
 <asp:Literal ID="litResults" runat="server" />
    </div>

and in code behind :-

protected void butRead_Click(object sender, EventArgs e)
    {
        readXML();
        lblStatus.Text = "";
    }

    private void readXML()
    {
        XDocument xDoc = XDocument.Load(Server.MapPath("~/People.xml"));
        var persons = from person in xDoc.Descendants("Person")
                      select new
                      {
                          Name = person.Element("Name").Value,
                          City = person.Element("City").Value,
                          Age = person.Element("Age").Value,
                      };
        litResults.Text = "";
        foreach (var person in persons)
        {
            litResults.Text = litResults.Text + "Name: " + person.Name + "<br />";
            litResults.Text = litResults.Text + "City: " + person.City + "<br />";
            litResults.Text = litResults.Text + "Age: " + person.Age + "<br /><br />";

        }
    }

    protected void butAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtName.Text == "" || txtCity.Text == "" || txtAge.Text == "")
                lblStatus.Text = "Please complete the form.";
            else
            {
                XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

                xmlDoc.Element("Persons").Add(new XElement("Person",
                    new XElement("Name", txtName.Text),
                    new XElement("City", txtCity.Text),
                    new XElement("Age", txtAge.Text)));

                xmlDoc.Save(Server.MapPath("People.xml"));
                lblStatus.Text = "Data successfully added to XML file.";
                readXML();
            }
        }
        catch
        {
            lblStatus.Text = "Sorry, unable to process request. Please try again.";
        }
    }

Hope this helps

Good Luck

Categories: Linq, XML

Get Last Inserted Identity with Stored Procedure using Linq

August 15, 2009 Leave a comment

Hi

try this example :-

let we have a stored procedure which will return the last inserted Record

1) Create new Project and add Linq to SQL  Classes and name it DataContext.dbml

2) Add your table and your Stored Procedure inside DataContext.dbml

Create PROCEDURE [proc_CountriesInsert]
(
 @CountryID smallint = NULL output,
 @CountryName nvarchar(50) = NULL,
 @xCurrency_ID smallint = NULL
)
AS
BEGIN
 
 INSERT
 INTO [Countries]
 (
  [CountryName],
  [xCurrency_ID]
 )
 VALUES
 (
  @CountryName,
  @xCurrency_ID
 )
 SELECT @CountryID = SCOPE_IDENTITY()
END

in code in button click :-

short ? CountryId=0;
DataContext.proc_CountriesInsert(ref CountryId,"xx",1);
 if (countryid.HasValue)
    {
        Label1.Text = "Inserted Value --> " + Convert.ToString(CountryId);
    }
    else
     {
       Label1.Text = "No Value ..";
     }

Hope this helps

Good Luck

Categories: Linq