Sunday, June 24, 2012

How to get Type of Exception in C#

Many times we have different ways to handle different kind of errors so we need to know the type of error that has occurred in the system. Here's a simple example in ASP.NET
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["usrPrivilege"].ToString().Equals("USER"))
            {
                //Your Code goes here
            }
        }
        catch (NullReferenceException ex)
        {
            Response.Redirect("~/login.aspx");
        }
        catch (AccessDeniedException ex) 
        {
          //Do something else
        }
        catch (System.Exception ex)
        {
               //Code for other type of exception
        }
    }

Friday, June 22, 2012

ASP.NET textboxes that take only numerical values as input

Following is a javascript code snippet for your ASP.NET test.aspx page. Please note the script checkNumber is for non-decimal numbers while checkNumber is for decimal numbers.


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>User Page</title>
    
    <script language="javascript" type="text/javascript">

function checkNumber(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    
    if(code==13)
    {
    
        
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)))
    {
        return false;
    }
    return true;
}
function checkNumberWithDecimal(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    if(code==13)
    {
    
        //var obj= getFrmObject(textBox);
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)||(code==46)))
    {
        return false;
    }
    return true;
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        <div style="float:left">Registration No</div>
        <div style="float:left"><asp:TextBox ID="txtRegNo" runat="server"></asp:TextBox></div>
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
And following is your code on

Page_Load

protected void Page_Load(object sender,EventArgs e)
{
      txtRegNo.Attributes.Add("OnKeyPress", "javascript:return                                     checkNumber(this,event);");

}     

Reading Excel File in C# dot Net



using System;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using Microsoft.Office.Interop.Excel;




private void Page_Load(object sender,EventArgs e)
{
      operateExcel("C:\\EXCEL.xls");
}
private void operateExcel(string pth)
    {
       
        DataSet dtset = new DataSet("MYEXCEL");
        try
        {
            //lvContent.Items.Clear();
            Workbook wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


            wbok = app.Workbooks.Open(pth, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //WorksheetClass wshts = (Worksheets)wbok.Worksheets;

            Sheets wshts = wbok.Worksheets;
            Worksheet wsht = (Worksheet)wshts.get_Item(1);
         

            System.Data.DataTable dtbl = new System.Data.DataTable("MYEXCEL");
            dtset.Tables.Add(dtbl);

            DataColumn col = new DataColumn();
         
            col.ColumnName = "COL1";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL2";
            dtbl.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "COL3";
            dtbl.Columns.Add(col);

           
            for (int i = 2; i < 10000 && wasLastnull < 3; i++)
            {
               
                Range rnge = wsht.get_Range("A" + i.ToString(), "I" + i.ToString());
                System.Array myvalues = (System.Array)rnge.Cells.Value2;
                System.Array vals = (System.Array)rnge.Cells.Value2;
                string a1 = "", a2 = "", a3 = "" ;
                try
                {
                   
                        a1 = vals.GetValue(1, 1).ToString();
                        a2 = vals.GetValue(1, 2).ToString();
                        a3 = vals.GetValue(1, 3).ToString();
                        DataRow dr = dtbl.NewRow();
                        dr["COL1"] = a1.ToString();
                        dr["COL2"] = a2.ToString();
                       dr["COL3"] = a3.ToString();
                      dtbl.Rows.Add(dr);
                       count = count + 1;
                    }

                catch (System.Exception ex)
                {
                    Label1.Text = ex.ToString() + "ERROR";
                }
           }
           
            app.Workbooks.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wsht);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(wbok);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
             
        }
        catch (System.Exception ex)
        {

        }
    }

Thursday, June 21, 2012

Display div alongside with links on mouse move and hide when mouse moves out

Literally I prefer to use ToolTip text or title attribute when I need to display simple information however many times we need a div element to do the trick to meet our business requirement. I had found following script in some site few months back but I do not remember which but with hope it might help others, I have pasted it here.

  <script type="text/javascript" language="JavaScript">

var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e)
       cX = e.pageX; cY = e.pageY;
}
function UpdateCursorPositionDocAll(e)
    cX = event.clientX; cY = event.clientY;
}
if(document.all) 
    document.onmousemove = UpdateCursorPositionDocAll; 
}
else 
    document.onmousemove = UpdateCursorPosition; 
}
function AssignPosition(d) {
if(self.pageYOffset) {
 rX = self.pageXOffset;
 rY = self.pageYOffset;
 }
else if(document.documentElement && document.documentElement.scrollTop) {
 rX = document.documentElement.scrollLeft;
 rY = document.documentElement.scrollTop;
 }
else if(document.body) {
 rX = document.body.scrollLeft;
 rY = document.body.scrollTop;
 }
if(document.all) {
 cX += rX; 
 cY += rY;
 }
d.style.left = (cX+10) + "px";
d.style.top = (cY+10) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d,cnt) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
dd.style.display = "block";
dd.innerHTML=cnt;
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") { dd.style.display = "block"; }
else { dd.style.display = "none"; }
}
</script>

The div Element

Setting text of the div element in runtime

protected void Page_Load(object sender,EventArgs e)
   {
    string content="I am loaded in runtime ";
    lnk1.Attributes.Add("onmouseover", 
"javascript:return ShowContent('myDiv','" + content + "'); return true;");
   lnk1.Attributes.Add("onmouseout", "javascript:return 
HideContent('myDiv'); return true;");

   }

Adding Controls in Run Time

There are many ways to add controls in runtime in ASP.NET, however the one I love is using the placeholder control. Its easy, you can place it inside the div element or td element of a table and add controls without worrying where the controls will appear inside the page. So add a placeholder inside the div element and add controls. Following code snippet shows you how to add Label Control during runtime

Adding Controls in runtime in C# ASP.NET

protected void Page_Load(object sender, EventArgs e) { addControls(); } protected void addControls(); { for(int i=0;i<5;i++) { Label lbl = new Label(); lbl.ID = "lbl" + app_code + "_" + priv_code; lbl.ToolTip = dsPriv.Tables[0].Rows[j][4].ToString(); lbl.Style.Add("margin-left", "40px"); lbl.Text = dsPriv.Tables[0].Rows[j][3].ToString(); PlaceHolder1.Controls.Add(lbl); LiteralControl lCntrl = new LiteralControl("
"); PlaceHolder1.Controls.Add(lCntrl); } }
and that's it

Tuesday, June 15, 2010

Fileupload inside UpdatePanel

I have a updatepanel in the master-page and fileupload control in the content page where it was not working despite my use of trigger
The I did the following trick
Step 1:
In the code file of the master page I did the following
public void RegisterPostbackTrigger(Control fullPostBack)
{
ScriptManager1.RegisterPostBackControl(fullPostBack);
}
Step 2:
In the HTML code of the content page I had following lines
Step 3:
Inside the page load event of content page I did the following
protected void Page_Load(object sender, EventArgs e)
{
try
{
((ASP.pages_admin_master_master)Page.Master).RegisterPostbackTrigger(btnUpload);

}
catch
{
}
}

Monday, May 24, 2010

IMPORTING EXCEL FILE INTO ASP.NET GRIDVIEW

protected void Button1_Click(object sender, EventArgs e)
{
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("ExcelImport.xls") + ";" +
"Extended Properties=Excel 8.0;";

OleDbConnection objXConn = new OleDbConnection(xConnStr);
string sql = "SELECT * FROM [Salary$]";
OleDbCommand cmd = objXConn.CreateCommand();
cmd.CommandText = sql;
OleDbDataAdapter adpt = new OleDbDataAdapter();
adpt.SelectCommand = cmd;
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();


}