Wednesday, December 29, 2010

Create a javascript ToolTip within 10 minutes for Asp.net page




Please visit my new Web Site WWW.Codedisplay.com



Sometimes we need to create handy javascript tooltip for client. Here in this article i will show how one can create a javascript tooltip within very short time by using DIV object. To do that here i use a DIV as a tooltip container. When i need to show the tooltip then i have set the DIV visibility style to 'visible' otherwise 'hidden'. Very simple right? Lets start:











Add an Aspx page in your project. Then add the below javascript method:
function DisplayToolTip()
        {
            document.getElementById('divToolTip').style.left = window.event.x;
            document.getElementById('divToolTip').style.top = window.event.y;

            document.getElementById('divToolTip').style.visibility = 'visible';
        }
        
        function HideToolTip()
        {
            document.getElementById('divToolTip').style.visibility = 'hidden';
        }

Now add the below HTML markup code:
<span id="spanName" style="font-weight: bold;border: solid 2px red;" onmouseover="javascript:DisplayToolTip();"
    onmouseout="javascript:HideToolTip();">THIS IS THE SPAN</span>


    <div id="divToolTip" style="position: absolute; visibility: hidden; z-index: 20;
    background-color: white; border: solid 1px Blue;">This is ToolTip Text</div>

Now run the page hope you will get desired output:
Javascript Tooltip

Please note that this script does not run into mozilla firefox but will work in IE & Opera as well. To do that in easy way download built in jquery tooltip which is available in the internet. This is only a faster development technique for IE developers.

Friday, December 3, 2010

Using Server.Transfer how to pass values from source page to destination page




Please visit my new Web Site WWW.Codedisplay.com



It's not possible to pass value using query string from source page to destination page when using Server.Transfer. To pass data or value from source page to destination page while using Server.Transfer you can use HttpContext object. To do that add two aspx pages in your project & give name source.aspx & destination.aspx. In source.aspx page place a LinkButton. And under the LinkButton Click event write the below code:

To learn Difference Between Response.Redirect vs Server.Transfer Click Here.









protected void Linkbutton1_Click(object sender, EventArgs e)

{

HttpContext CurrContext = HttpContext.Current;

CurrContext.Items.Add("Name", "Shawpnendu Bikash Maloroy");

CurrContext.Items.Add("Address", "Dhaka, Bangladesh");

Server.Transfer("Destination.aspx");

}

In Destination.aspx Page under Load event write the below code:
protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

HttpContext CurrContext = HttpContext.Current;

Response.Write(CurrContext.Items["Name"].ToString()+" ");

Response.Write(CurrContext.Items["Address"].ToString());

}

}

Now run the source.aspx page & click on the LinkButton. You will get below output:

Server.transfer

Hope now you can understand how to transfer or pass data between pages while using Server.Transfer.

Difference Between Server.Transfer vs Response.Redirect




Please visit my new Web Site WWW.Codedisplay.com



There is a common question for developers in Asp.net interview board that "What is the difference between Response.Redirect and Server.Transfer". In a common term we can use both to redirect the user from source page to destination page. But there are some differences in between Response.Redirect and Server.Transfer, which i want to share with you.

Response.Redirect:
1. A round trip occurs to the client before loading the destination page, which means after redirecting a page from source page to destination page a round trip occur into the client to update the address bar and history of the client browser. And also the destination page will be loaded by initiating a new request which is the 2nd request to the server.
2. To pass data in this mechanism you can easily use Query String or Session value.




Server.Transfer:
1.It is a single request from source page to destination page. The destination.aspx will be loaded from the server without a second request. Means it will not update the address bar and history of the browser.
2. You will get better performance.
3. You cannot use Query String.
4. To pass data between souce.aspx page to destination.aspx by using HttpContext object. Click here to use HttpContext object.
5. You can also use session object to transfer data.
6. Users can not bookmark the destination.aspx page.

Friday, November 26, 2010

How to bind XML File or XML DataSource to a DataList Control in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



DataList control is an important control in Asp.Net applications. Most of the times we need to bind DataList control from a Database using Ado.Net datasource. But sometimes we need to bind XML file as Datasource into a DataList control. Here in this article i will demonstrate how one can bind XML data into a DataList control using the datasource XmlDataSource. The output will be:

Bind XML data into DataList controlo

To do the above example we need to write an XML file like:
<?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <Customer>
    <Name>Shawpnendu Bikash Maloroy</Name>
    <Address>Uttara, Dhaka</Address>
    <City>Dhaka</City>
    <Phone>011789657</Phone>
  </Customer>
  <Customer>
    <Name>Bimolandu Bikash Maloroy</Name>
    <Address>Sonaimuri, Noakhali</Address>
    <City>Noakhali</City>
    <Phone>019789687</Phone>
  </Customer>
  <Customer>
    <Name>Purnendu Bikash Maloroy</Name>
    <Address>FirmGate, Dhaka</Address>
    <City>Dhaka</City>
    <Phone>018788767</Phone>
  </Customer>
  <Customer>
    <Name>Shadesh Chandra Chanda</Name>
    <Address>Maijdee, Noakhali</Address>
    <City>Noakhali</City>
    <Phone>015787597</Phone>
  </Customer>
  <Customer>
    <Name>Sajal Chandra Chanda</Name>
    <Address>Maijdee, Noakhali</Address>
    <City>Noakhali</City>
    <Phone>019734557</Phone>
  </Customer>
</Customers>

Now add an aspx page into your project & modify the HTML markup like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataList_XML.aspx.cs" Inherits="DataList_XML" %>

<!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>An Example of Binding XML Datasource into DataList Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1"> 
        <HeaderTemplate>Customer Name</HeaderTemplate>
        <ItemStyle BackColor="Gray" ForeColor="Yellow" />
        <AlternatingItemStyle BackColor="Silver" />
        <ItemTemplate>
            <%# XPath("Name")%>
        </ItemTemplate>
    </asp:DataList>
    
    <asp:XmlDataSource ID="XmlDataSource1" runat="server" 
        DataFile="Customers.xml" 
        XPath="//Customers/Customer">
    </asp:XmlDataSource>
    
    </div>
    </form>
</body>
</html>

Now run the page. Hope you will get your desired output.

Web Parts Drag & Drop functionality in Asp.net Pages




Please visit my new Web Site WWW.Codedisplay.com



It’s my first article on Asp.net Web Parts. Basically it’s an introduction article how one can start to learn the high end feature of Asp.net web parts. As you knew that most of the portal contains several block. In general the end user can not change the page block orientation or positioning which is termed as personalization. The Asp.net Web Parts gives us the personalization facility with little code. That’s why the Web Parts is necessary to learn. In my below example I will show you how developers can provide the Drag & Drop facility to personalize end user UI.

To do that you have to understand only two things. The first one is WebPartManager & the second one is WebPartZone.

WebPartManager:
This Asp.net server control manages the state of the zones per user basis. The most important part is you must place an Asp.net WebPartManager server control in each page. But the situation is different for master page as we know. The another importance of the WebPartManager server control is to maintain the communication between different elements contained in a zone or within different zone. Let’s say in one zone you display the product list & in another zone you display the product details. Which means zones are dependent on each other. If you select a product in first zone then you must change the product details in next zone. For such type of cases communication is required done by WebPartManager.

WebPartZone:
WebPartZone contains the elements that you want to Drag & Drop. You can Drag & Drop contains from one zone to another zone. The WebPartManager just controls the zones. You cannot put zone contents into the rest of the pages which does not contain another zone.

Note:
Please note that by default Asp.net creates ASPNETDB.MDF and stores it in the App_Data folder.

Start Example:
Add an Aspx page in your project. Write the below HTML markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebParts.aspx.cs" Inherits="WebParts" %>

<!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>An Example on Asp Web Parts</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:WebPartManager ID="WebPartManager1" runat="server" >
        </asp:WebPartManager>
        <table border="1">
        <tr style="background:Blue">
        <td colspan="3">
        <h1 style="color:White">Welcome to shawpnendu.blogspot.com</h1> 
        </td>
        </tr>
        
        <tr>
        <td>
        <asp:WebPartZone ID="WebPartZone1" runat="server" HeaderText="Enter Name">
            <ZoneTemplate>
            <asp:TextBox runat="server" ID="txtLastName" Title="Enter Last Name:"></asp:TextBox>
            </ZoneTemplate>
        </asp:WebPartZone>
        </td>
        
        <td>
        <asp:WebPartZone ID="WebPartZone2" runat="server" HeaderText="Enter Name">
            <ZoneTemplate>
            <asp:TextBox runat="server" ID="txtMiddleName" Title="Enter Middle Name:"></asp:TextBox>
            </ZoneTemplate>
            </asp:WebPartZone>
        </td>
        
        <td>
        <asp:WebPartZone ID="WebPartZone3" runat="server" HeaderText="Enter Name">
            <ZoneTemplate>
            <asp:TextBox runat="server" ID="txtFirstName" Title="Enter First Name:"></asp:TextBox>
            </ZoneTemplate>

        </asp:WebPartZone> 
        </td>
        
        </tr>
        </table>
    </div>
    </form>
</body>
</html>

Please note that control Title property will represent the section name of a zone.

Now run the page & you will get the below output:
Asp.Net Web Parts Introduction

In this scenario you will not get the Drag & Drop facility. Only get Minimize & close option in each zone. Because the Drag & Drop facility based on WebPartManager DisplayMode property. The default value is "Browse". If you change the mode from "Browse" to "Design" mode then you will get Drag & Drop Facility like below:

Asp.Net Web Parts Drag & Drop

To change the WebPartManager DisplayMode property just write the below code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            WebPartManager1.DisplayMode = WebPartManager1.SupportedDisplayModes[1];
            Response.Write("Current MODE= " + WebPartManager1.SupportedDisplayModes[1].Name + "");
        }
    }

Ok now test the page & start to learn Asp.Net Web Parts. Drag one content & Drop the selected content into another zone. Now run the page again & the interesting thing is the page retain your last zone orientations. Because Asp.net stores your action into the ASPNETDB.MDF. Later on i will discuss zone to zone communication steps.

Saturday, November 13, 2010

How to Install Firebug Add-on in your Mozilla Firefox Browser




Please visit my new Web Site WWW.Codedisplay.com



The web developers most important tool is Firebug. It's basically a Mozilla Firefox add-on which makes our I mean developers life is very ease to debug and develop web pages. To inspect HTML or ASPX page elements even javascript one can easily use the firebug add-on. The firebug application provide us to detect bugs on any website. It can identify any tag mistakes or CSS conflicts that you have made in your page incorrectly. Firebug also has a live modification feature where you can change the code & see the effect immediately.

To install Firebug in your Mozilla Firefox follow the below steps:

1. Open Firefox Browser and click into the Tools Menu. Then select Add-ons.
Firefox_tools Menu

2. Now a popup window will open. Click on Browse All Add-ons at the right side of the popup window.
Firefox_browse_Add-ons

3. Now a new tab will appear with a search box. Write Firebug and click on continue button.
firebug search

4. Now select the Firebug Add-on from the list and click on “Add to FireFox button”.
pre installation of firebug

5. A new popup window will open. Click on Install Now button.
Installation of firebug

6. That's it. You have successfully installed firebug add-on in your Mozilla Firefox browser.

To ensure the installation of firebug add-on please restart the FireFox. Now you will find a logo in the bottom left or bottom right corner of your browser. To test the firebug load the page where you stuck and click on the logo to continue your inspection.

Hope now you will be ready to use the firebug application and start detecting those bugs that are stopping your design from showing the way you want it.

Wednesday, November 3, 2010

How to use optional parameter in SQL server SP




Please visit my new Web Site WWW.Codedisplay.com



When you are going to write a generic SP for any business purpose you may realize the necessity of optional parameter. Yes Sql server gives us the opportunity to use optional parameter in SP arguments. You may write a SP with 3 arguments but based on your business rule you may pass one or two or three valuse as you want. This policy not only ease our life but also help us to write short SP. Here in this article i will discuss how one can create a optional list SP & execute thie SP or stored procedure.










Ok first write a SP with two optional field like below:
ALTER procedure Optional_Procedur 
@Name varchar(200)=null,
@Age int=null
As
BEGIN
if @Name is not null  
 print 'Your Name Is '+@Name
if @Age is not null
 print 'Your Age '+Convert(varchar(3),@Age)
END

Now you can call the SP in many different ways like:
exec Optional_Procedur 'Shawpnendu'
print '-----------------------------'
exec Optional_Procedur 'Shawpnendu',32
print '-----------------------------'
exec Optional_Procedur @Name='Shawpnendu'
print '-----------------------------'
exec Optional_Procedur @Age=32


The query output is given below:

Your Name Is Shawpnendu
-----------------------------
Your Name Is Shawpnendu
Your Age 32
-----------------------------
Your Name Is Shawpnendu
-----------------------------
Your Age 32

I.E. You can send parameter specific values or sequential values or you are not bound to send parameter values in this regard.

Monday, November 1, 2010

Error: 'object could not be found' or 'invalid object name'?




Please visit my new Web Site WWW.Codedisplay.com



As a Developer i thought you may experience one of two errors frequently, even though you thought the object already exist. The error like below:

Msg 208, Level 16, State 1, Line 1
Invalid object name 'Table/View Name'.

OR

Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure ''.






Solution:
To Avoid Such type of error keep in mind always the following considerations:

1. The connecting user does not have SELECT, UPDATE, INSERT, DELETE, EXEC permissions on that object/objects.

2. your are logging/connecting as a different user that you have expected.

3. Referencing the object without an owner name prefix may raise this error;

4. your connected database is wrong;

5. May be you have written wrong object name or spelled incorrectly.

How to determine whether a table is exist or not in Sql Server database




Please visit my new Web Site WWW.Codedisplay.com



In some cases we need to identify whether a table is exist or not in a sql server database. This is very simple & now i am sharing with you. Hope it will works like a handbook for you.













Query:
IF EXISTS (SELECT 1 
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE='BASE TABLE' 
    AND TABLE_NAME='tablename') 
        SELECT 'table exists.' 
ELSE 
        SELECT 'table does not exist.'

Hope it will help you.

Sunday, October 10, 2010

Jquery to read DatakeyNames value of Selected Rows of GridView in Asp.Net




Please visit my new Web Site WWW.Codedisplay.com



As we know GridView is a very popular control. We always experiment to enhance the GridView control to provide better experience to user. Since javascript is also a popular clientside language, most of the times we use this in client side operations like validation, Row coloring, cell coloring etc. Now a days Jquery is more popular so that in this article i will explain how you can capture the selected rows of a GridView control and also read the datakeyname values using JQuery. So at first i will tell you how we capture selected rows of a GridView. In this example i don't consider the built in Select command. Instead of select command here i use checkbox to select rows by user. The another important tip is we cannot directly access DataKeyNames values of a GridView. To get the value, here I will use a template column to store the same DataKeyValue in a hiddenfield. After that through iteration by Jquery I will read the hiddenfield values which looks alike datakeynames values.

For selecting/deselecting all checkboxes of a GridView using Javascript click here.


My example output look like below:
GridView_Datakeynames_jQuery

The GridView Control HTML will be:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">   
            <Columns>   
                <asp:TemplateField>   
                    <ItemTemplate>   
                        <asp:CheckBox ID="chkSelect" runat="server" />   
                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />   
                    </ItemTemplate>   
                </asp:TemplateField>   
                <asp:TemplateField>   
                    <HeaderTemplate>   
                        Name   
                    </HeaderTemplate>   
                    <ItemTemplate>   
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>   
                    </ItemTemplate>   
                </asp:TemplateField>   
            </Columns>   
        </asp:GridView>

The Jquery Script also given below:
<script type="text/javascript">   
    $(document).ready(function() {  
    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');   
    $('#<%= cmdGetData.ClientID %>').click(function (e) {
        var DataKeyName="";  
        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {   
            if(DataKeyName.length==0)
            {
                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
            }
            else
            {
                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
            }
        });   
        alert(DataKeyName);
        return false;   
    });   
   });   
</script>

Now Bind the GridView data within Page_Load Event:
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("ID");
        dt.Columns.Add("Name");

        DataRow oItem = dt.NewRow();
        oItem[0] = "1";
        oItem[1] = "Shawpnendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "2";
        oItem[1] = "Bimalendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "3";
        oItem[1] = "Purnendu Bikash Maloroy";
        dt.Rows.Add(oItem);

        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

The complete markup language of this example is:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_DataKeyNames_Jquery.aspx.cs" Inherits="GridView_DataKeyNames_Jquery" %>

<!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>Get Selected rows of a GridView using Jquery</title>
<script src="Script/jquery.js" type="text/javascript"></script>

<script type="text/javascript">   
    $(document).ready(function() {  
    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');   
    $('#<%= cmdGetData.ClientID %>').click(function (e) {
        var DataKeyName="";  
        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {   
            if(DataKeyName.length==0)
            {
                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
            }
            else
            {
                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
            }
        });   
        alert(DataKeyName);
        return false;   
    });   
   });   
</script>   
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">   
            <Columns>   
                <asp:TemplateField>   
                    <ItemTemplate>   
                        <asp:CheckBox ID="chkSelect" runat="server" />   
                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />   
                    </ItemTemplate>   
                </asp:TemplateField>   
                <asp:TemplateField>   
                    <HeaderTemplate>   
                        Name   
                    </HeaderTemplate>   
                    <ItemTemplate>   
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>   
                    </ItemTemplate>   
                </asp:TemplateField>   
            </Columns>   
        </asp:GridView>   
  
        <br />   
        <asp:Button ID="cmdGetData" runat="server" Text="Get Data" />    
    </div>
    </form>
</body>
</html>

Hope you got my trick & now you can read get selected rows of a GrodView control using jQuery.

Wednesday, October 6, 2010

Jquery to Get selected items from CheckBoxList




Please visit my new Web Site WWW.Codedisplay.com



In many forums i found that developers asking this question. I have answered in many forums and now i decide to write a post on how to get selected items or selected values of checkboxlist using Jquery. This is not an easy job. You need to loop through the checkbox list to get all selected items/values. Here if you look at my code example you will get the loop structer. Here i use comma separator to identify unique selected items. The output screen is given below:

CheckBox List With Jquery

Jquery Method:
<script type="text/javascript">
    $(document).ready(function() {
    $('#cmdGet').click(function()
    {
        var values='';
        $('#<%=CheckBoxList1.ClientID %> input[type=checkbox]:checked').each(function()
        {
            if(values.length==0)
            {
                values = $('label[for=' + this.id + ']').html();
            }
            else
            {
                values += ","+$('label[for=' + this.id + ']').html();
            }
        });
        alert(values);
        return false;
    });
    });  
    </script>
Complete HTML Markup language to run the example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckboxList_Jquery.aspx.cs" Inherits="CheckboxList_Jquery" %>

<!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>ASP.NET Checkboxlist get values in client side using JQuery</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
    $('#cmdGet').click(function()
    {
        var values='';
        $('#<%=CheckBoxList1.ClientID %> input[type=checkbox]:checked').each(function()
        {
            if(values.length==0)
            {
                values = $('label[for=' + this.id + ']').html();
            }
            else
            {
                values += ","+$('label[for=' + this.id + ']').html();
            }
        });
        alert(values);
        return false;
    });
    });  
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal">
            <asp:ListItem Text="One" Value="1"></asp:ListItem>
            <asp:ListItem Text="Two" Value="2"></asp:ListItem>
            <asp:ListItem Text="Three" Value="3"></asp:ListItem>
            <asp:ListItem Text="Four" Value="4"></asp:ListItem>
            <asp:ListItem Text="Five" Value="5"></asp:ListItem>
        </asp:CheckBoxList>
        <hr />
        <asp:Button runat="server" ID="cmdGet" Text="Get Selected Values" />
    </div>
    </form>
</body>
</html>
Now you got an idea of how to access the values in client-side. Hope it will help you to findout the selected items of checkbox list using jquery.

Script tested for:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Tuesday, October 5, 2010

How to Set Get RadioButtonList Selected Value using Jquery




Please visit my new Web Site WWW.Codedisplay.com



In one of my previous post i have written an article on "How to get set RadioButtonList value using javascript". Since Jquery now a popular scripting language thats why in this post i am going to explain how one can access or get or read or set RadioButtonList value using Jquery. Using javascript we can directly use RadioButonList click handler but in Jquery we can't. So what is the solution? Yes every problem has solution. Here i am using a trick to handle RadioButtonList click handler. First add a DIV tag. And then within the DIV tag place your RadioButtonList. After that when user click on the div tag we will fire a div click event & will handle RadioButtonList select value. My example output is given below:

RadioButtonList Jquery

For example the HTML Markup Code is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Radiobuttonlist_jquery.aspx.cs" Inherits="Radiobuttonlist_jquery" %>

<!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>Jquery to get set RadioButtonList Value</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
</head>

<body>
    <form id="form1" runat="server">
        <div id="RadioDiv">
           <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Value="One">1</asp:ListItem>
                <asp:ListItem Value="Two">2</asp:ListItem>
                <asp:ListItem Value="Three">3</asp:ListItem>
                <asp:ListItem Value="Four">4</asp:ListItem>
                <asp:ListItem Value="Five">5</asp:ListItem>
            </asp:RadioButtonList>
            <hr />
        </div>
        <input id="cmdSetValue" type="button" value="Set Four" />
        <hr />
        <div id="info" style="font-weight:bold"></div>    
    </form>
</body>
</html>

Now add the below Jquery script:
<script language="javascript">
         $(document).ready(function() {
             $('#RadioDiv input').click(function() {
                 $("#info").text('Selected Value: '+$("#RadioDiv input:radio:checked").val());
            });
            
            $("#cmdSetValue").click(function() {
                $('#<%=RadioButtonList1.ClientID %>').find("input[value='Four']").attr("checked", "checked");
                $('#RadioDiv input:radio:checked').trigger('click');
            });

        });  
    </script> 

Now run the page & hope you will understand the technique that i have applied to capture RadioButtonList click event as well as setting a SelectedValue to the RadioButtonList.

Script tested for:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

How to Display / Show Hide toggle a Div using Jquery




Please visit my new Web Site WWW.Codedisplay.com



The man who starts to learn Jquery, basically this post is for you. As a developer i knew that in most web applications we need to do the same job many times. Previously i have explained how one can display/show hide a div using Javascript. For Javascript version please click here. But recent days we were very familiar with Jquery & love to write Jquery method instead of Javascript. In this article i will basically show you how you can display show hide Div content using jquery. To do that first add an aspx page in your project. Then write the link to your jquery libraray. Now add a text link (named Show/Hide Div) in your page. Also add a div tag on your page. Our purpose is when user click on Show/Hide Div link then if the corresponding DIV which you want to display or hide is hidden then the jquery script will display the DIV otherwise hide. Please have a look of my example code snapshot:

Toggle Div Jquery


If you are looking for javascript code to toggle the DIV CLICK HERE.


The Jquery script is given below:
<script type="text/javascript">
        $(document).ready(function(){

            $('#DIV1').hide();
            $('a#lnkShowHide').click(function(){
                $('#DIV1').toggle('slow');
                return false; /** not necessary if you add "#" into Achor href.**/
            });
        });

</script>
The complete HTML markup code is given below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Show_hide_Div_Jquery.aspx.cs" Inherits="Show_hide_Div_Jquery" %>

<!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>How to display hide DIV tag using Jquery</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
<script type="text/javascript">

        $(document).ready(function(){

            $('#DIV1').hide();
            $('a#lnkShowHide').click(function(){
                $('#DIV1').toggle('slow');
                return false; /** not necessary if you add "#" into Achor href.**/
            });
        });

</script>
    
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <a id="lnkShowHide" href=""  name="lnkShowHide">Show/Hide Div</a>
            <div id="DIV1">
                <p>Some div content here<br/>Some div content here</p>
            </div>
        </div>
    </form>
</body>
</html>
Hope now you can toggle div using Jquery smoothly.

Script tested for:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Thursday, September 30, 2010

Jquery to get set read access IFrame content TextBox Value Data




Please visit my new Web Site WWW.Codedisplay.com



As you know that this days smart developers doesn't use IFRAME. But in our job always developers need to handle legacy systems. I found such type of legacy application. Now i am trying to modify the user requirement. To do that i need to read or access IFrame content as well as get or put some data from parent page to IFRAME. Since i did it thats why i want to share with you how one can access/read/get IFrame content controls like TextBox value as well as set the value from parent page to IFRAME using JQUERY.

Here is a simple output screenshot of my example:
IFRAME_Jquery

To complete this example first create the below asp.net aspx page. Which we used within the IFRAME:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Iframe_Page_Content.aspx.cs" Inherits="Iframe_Page_Content" %>

<!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>Child page placed into the IFrame</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label runat="server" ID="lblInfo">Iframe TextBox: </asp:Label>
    <asp:TextBox runat="server" ID="txtInfo"></asp:TextBox>
    </div>
    </form>
</body>
</html>
Now create the below asp.net master page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="IFRame_Jquery.aspx.cs" Inherits="IFRame_Jquery" %>

<!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>How to Get Set Iframe Content Like TextBox Control Value Text Data</title>
    <script src="Script/jquery.js" type="text/javascript"></script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <iframe id="uploadIFrame" scrolling="no" frameborder="0" style="border-style: none; margin: 0px; width: 100%; height: 40px;" src="Iframe_Page_Content.aspx"></iframe>    
        <asp:Button runat="server" ID="btnSet" Text="Hello Jquery Developers !!" />
        <asp:Button runat="server" ID="btnGet" Text="Click to read Iframe TextBox Data !!" />
    </div>
    </form>
</body>
</html>
Now use the below JQUERY to get set value:
<script language="javascript">
        $(document).ready(function() {
            $("#btnSet").click(function() {
                var $currIFrame = $('#uploadIFrame'); 
                $currIFrame.contents().find("body #txtInfo").val($('#btnSet').val());
                return false;
            });
        });

        $(document).ready(function() {
            $("#btnGet").click(function() {
                var $currIFrame = $('#uploadIFrame'); 
                alert($currIFrame.contents().find("body #txtInfo").val());
                return false;
            });
        });

    </script>

Hope one can access IFRAME content as well as set the value from parent page to IFrame using JQUERY.

Code Explanation:
Here I have created an Object named currIFrame which holds the full IFrame reference. The contents() method is used to get full HTML code inside the IFRAME.The Find() method is used to find out the element. The rest of the code is self explanatory. Hope you can understand.

Script tested for:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Monday, September 27, 2010

How to merge all files into one file using DOS command




Please visit my new Web Site WWW.Codedisplay.com



Some days ago one of my friend ask me a problem that he needs to import csv file to a SQL Server database. But the problem is there is a huge number of small files. He does not want to import one by one. He needs to merge or together all files in a single file so that he can import using SQL Server import wizard only one file. Since it was a one time job for reconcilation, I suggest him use a DOS command to merge all files into a single or one file. The DOS command is given below:










For example, you can join file1.txt and file2.txt to a new file named file3.txt:
copy/b file1.txt +file2.txt file3.txt
OR:
copy/b *.txt newfilename.txt
OR for all files in a folder:
copy/b * "newfilename_with_path"

Tuesday, September 21, 2010

Jquery to get SelectedValue SelectedIndex SelectedText of a DropdownList in Asp.net




Please visit my new Web Site WWW.Codedisplay.com



When you bind a DropdownList by data sometimes it may require to do something in the client side using javascript or jquery. To read the same post using javascript click here. In this article i will show you how one can get DropdownList SelectedValue, SelectedText & SelectedIndex. So that you can now play with Asp.net DropdownList control. The output like below:

Drodwnlist jquery

An example of complete code is given below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How to get Selected value, Selected index & Selected text of a DropDownList</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    
    
<script type="text/javascript">
        $(function () {
            $('select[id$=DropDownList1]').bind("change keyup", function () {
                $('#info').html(
                "<b>Selected Value:</b> " + $('#<%= DropDownList1.ClientID%>').val() +
                "<br />" +
                "<b>Selected Index:</b> " + $('#<%= DropDownList1.ClientID%>').get(0).selectedIndex +
                "<br />" +
                "<b>Selected Text:</b> " + $('select[id$=DropDownList1] :selected').text());
            });
        });
    </script>
        
</head>
<body>
    <form id="form1" runat="server">
    <div>
<h2>To display Selectedvalue, Selectedindex & Selectedtext please select an item from the DropDownList</h2>
        <asp:DropDownList ID="DropDownList1" runat="server" >
            <asp:ListItem Text="One" Value="1"></asp:ListItem>
            <asp:ListItem Text="Two" Value="2"></asp:ListItem>
            <asp:ListItem Text="Three" Value="3"></asp:ListItem>
            <asp:ListItem Text="Four" Value="4"></asp:ListItem>
            <asp:ListItem Text="Five" Value="5"></asp:ListItem>
        </asp:DropDownList>
        <hr /><br />
        <div id="info"></div>    </div>
    </form>
</body>
</html>

Code explanation:
The line $('#<%= DropDownList1.ClientID%>').val() will return you the selectedtext.
The line $('#<%= DropDownList1.ClientID%>').get(0).selectedIndex will return you the selectedindex
The line $('select[id$=DropDownList1] :selected').text()) will return you selectedtext.

Note:
Here i used two event change & keyup because the change event works in IE wheres keyup event works for Mozilla, Chrome and Safari.

Script Tested for the following browsers:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Thursday, September 16, 2010

How to merge two or more files using C#




Please visit my new Web Site WWW.Codedisplay.com



Few days ago i have a requirement to make a processing engine which will download, decode & staging almost 70k+ ASN files. So that i have developed an ASN Decoder using Turbo C. Then make a DLL to use this decoder in my C# project. Everything is good but one problem is that my processing exe will take almost 6 hours to process all files. After reviewing my source code i found that each time my ASN Decoder DLL open a single file then decode it then close the file & also create a csv file for bulk insert into my database. I took a decission to reduce the time for open & closing a file. How i can do it? I made it by merging two or more or mutiple ASN files in a single file. So that my DLL need to open almost 1/3rd of files than earlier & my procesiing now takes only 2 hours. If you are facing such type of problem then you can follow my way.







C# Source code for merging mutiple files:
private void Form1_Load(object sender, EventArgs e)
        {
            string sASN1 = @"11.asn";
            string sASN2 = @"22.asn";

            FileStream FStream1 = null;
            FileStream FStream2 = null;

            FStream1 = File.Open(sASN1, FileMode.Append);
            FStream2 = File.Open(sASN2, FileMode.Open);
            byte[] FStream2Content = new byte[FStream2.Length];
            fs2.Read(FStream2Content, 0, (int)FStream2.Length);
            FStream1.Write(FStream2Content, 0, (int)FStream2.Length);

            MessageBox.Show("Merging Successfully ended!");

            FStream1.Close();
            FStream2.Close();
        }


Happy coding !!

Wednesday, August 4, 2010

How to prevent avoid Session Timeouts in an Asp.Net C# vb.net Page




Please visit my new Web Site WWW.Codedisplay.com



As we knew that its a very big problem specially when developers provide a very large entry page to users. It will be Irritating for users after entering all data & then session timeout occur. To prevent or avoid session timeout problem, there is no fixed or specific or direct way to handle. But one can handle this problem using javascript asynchronous call. But one thing keep in mind that time to execute the javacript method must be less than your session timeout time. Otherwise the method will not work. So, carefully set the time aganist IIS or web.config file session time. The cross-browser javascript method is given below:










<script language="javascript" type="text/javascript"> 
function Prevent_Session_Timeout() 
{ 
var callerurl = "Prevent_Session.aspx"; 

if (window.XMLHttpRequest) 
{ 
xhttp = new XMLHttpRequest() 
} 
else 
{ 
xhttp = new ActiveXObject("Microsoft.XMLHTTP") 
} 
xhttp.open("POST", callerurl, true); 
xhttp.send(""); 

window.setTimeout("Prevent_Session_Timeout();", 60000); 
} 

//Initial calling
Prevent_Session_Timeout(); 
</script> 

Important Notes:
1. Just create an aspx page named Prevent_Session.aspx. Because this page will be internally called by the above javascript method without any reflection to user.
2. You must set the window.setTimeout time parameter which never exceed the session timeout time of your project.
3. Paste the code in your main master page so that you need not write the code for each aspx page.

Script Tested for the following browsers:
1. Internet Explorer (IE)
2. Mozilla Firefox
3. Opera
4. Google Chrome

Tuesday, August 3, 2010

Maintaining Scroll Position after Asp.Net Page PostBack




Please visit my new Web Site WWW.Codedisplay.com



Sometimes we need to Maintain scroll position after page postback specially if the page is a large page & user need to work in the middle portion of the page. In this article i will give you a simple tips on How to maintain Scroll Position after Asp.Net Page PostBack. To do that in the Page Directive of your large Asp.Net Page, add the property 'MaintainScrollPositionOnPostback' and set its value as 'true'.












For Example:
<%@ Page Language="C#" CodeFile="Default.aspx.cs" MaintainScrollPositionOnPostback="true" Inherits="_Default" %> 
Now, the page will maintain the scroll bar position in the same location as it is before postback.

Monday, August 2, 2010

Error: Specified string is not in the form required for an e-mail address




Please visit my new Web Site WWW.Codedisplay.com



This error may occur when you are working with .net 1.1 means when using the namespace Sytstem.Web.Mail. If we want to send email to multiple or more than one person usually we use like:

To=aaaaaaa@gmail.com;bbbbbbbb@gmail.com;ccccccccc@gmail.com;

This will work in the namespace Sytstem.Web.Mail because here we use semicolon to split or separate email ID's.

But the ERROR: "Specified string is not in the form required for an e-mail address" will appear when we use semicolon as a separator in .net 2.0. Because the namespace System.Net.Mail in .net 2.0 framework will use comma as the email separator instead of semicolon. So we will use like below:

To="aaaaaaa@gmail.com,bbbbbbbb@gmail.com,ccccccccc@gmail.com";

Hope now your problem has been resolved.

Syntax of Shrinking SQL Server database mdf and log file




Please visit my new Web Site WWW.Codedisplay.com



The below code snippet will help you to shrink the database. Run the code snippet through your SQL Server query analyser.
















backup log <database_name> with truncate_only 
use <database_name> 
dbcc SHRINKFILE (<database_name_Log>,2) 
dbcc ShrinkDatabase (<database_name>, 2)

Wednesday, July 28, 2010

How to bind or populate Dropdownlist from XML file




Please visit my new Web Site WWW.Codedisplay.com



Few days ago i got an email from one of my reader. He wants more article on XML specially on Dropdownlist. Here in this article i will explain how one can bind or populate XML data into a Dropdownlist control. Asp.net DataSet provide us a method named ReadXml where we can initially load XML file. After that we can populate Dropdownlist DataTextField & DataValueField by DataSet default view table. To do the example first add an aspx page in your project then add a Dropdownlist control. After that add an XML file like below:









<?xml version="1.0" encoding="utf-8" ?>
<Products>
  <Product>
    <ID>1</ID>
    <Name>Lux</Name>
  </Product>
  <Product>
    <ID>2</ID>
    <Name>Harpic</Name>
  </Product>
  <Product>
      <ID>3</ID>
      <Name>Dove</Name>
  </Product>
  <Product>
      <ID>4</ID>
      <Name>Sunsilk</Name>
  </Product>
  <Product>
      <ID>5</ID>
      <Name>Pentine</Name>
  </Product>
</Products>

And then under page_load event write the below code:
using System;
using System.Data;

public partial class Dropdownlist_XML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet RS = new DataSet();
            RS.ReadXml(Server.MapPath("~/ProductList.xml"));
            
            DataView dv = RS.Tables[0].DefaultView;

            //Sorting by column name "Name" defined in XML file 
            dv.Sort = "Name";

            // Set the DataTextField and DataValueField
            DropDownList1.DataTextField = "Name";
            DropDownList1.DataValueField = "ID";

            DropDownList1.DataSource = dv;
            DropDownList1.DataBind();
        }
    }
}

Run the page to see that the Dropdownlist bind data as per XML file data.

Monday, July 26, 2010

Apply CSS to create Image Border




Please visit my new Web Site WWW.Codedisplay.com



Sometimes Asp.net developers need to enhance the UI by using image border. Though it's a bit easy in Asp.net image controls by using SKIN to manage image borders but it will be a bit difficult to manage HTML image control without CSS. Here in this post i will show you how one can apply CSS in both Asp.net image control and HTML image control. To do that first write the below CSS:











<style type="text/css">
    .imageCSS
 {
    padding: 3px;
    background-color: #FF0000;
 }
    </style>

Asp.Net Image Control:
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Image ID="Image1" runat="server" CssClass="imageCSS" ImageUrl="images/blue_flower.jpg" />
    </div>
    </form>
</body>

HTML Image Control:
<body>
    <form id="form1" runat="server">
    <div>
        <img src="~/Images/blue_flower.jpg" id="Image2" class="imageCSS" runat="server" />
    </div>
    </form>
</body>

Hope it will help.

Sunday, July 25, 2010

How to convert ArrayList to Array in Asp.net C# VB.Net




Please visit my new Web Site WWW.Codedisplay.com



In many cases developers have to create ArrayList to achieve dyanamic array functionalities. But sometimes you may need to convert the ArrayList to an array. For example if you are wnat to trnsfer csv data to ORACLE database then if you use bindarray then the conversion is required. Otherwise you won't to insert data into oracle databse. This is only one scenario but for lot of reasons you may need such type of conversion. Here in this article i will show you how you can convert ArrayList to Array.


CLICK HERE to read how to Create Dynamic Array.







C# Code Example:
using System;
using System.Collections;

public partial class Dynamic_Array : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList Dynamic_List = new ArrayList();
       
        for(int i=0; i<5; i++)
            Dynamic_List.Add(i);

        //Convert Here
 int[] array = (int[])Dynamic_List.ToArray(typeof(int));

        for(int i=0;i<=array.GetUpperBound(0);i++)
            Response.Write(array[i].ToString()+"</BR>");
    }
}

VB.NET Code Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Dynamic_List As New ArrayList()
        Dim i As Integer

        For i = 0 To 5
            Dynamic_List.Add(i)
        Next i

        // Convert here
        Dim array() As Integer
        array = DirectCast(Dynamic_List.ToArray(GetType(Integer)), Integer())

        For i = 0 To 5
            Response.Write(array(i).ToString() + "</BR>")
        Next i

    End Sub

Creating Using Dynamic Array's in Asp.Net C# VB.Net




Please visit my new Web Site WWW.Codedisplay.com



In some cases developers need to use dynamic arrays in Asp.net. But it’s not straight forward as like VB. If you were a VB developer then you knew that for dynamic array's VB uses REDIM keyword to generate dynamic array's. Here in this post i will discuss how developer can use dynamic arrays in asp.net pages. Basically there is no straight forward way to use but you can achieve the dynamic size by using a collection named ArrayList. The ArrayList collection provide us to add any type of object (int, float, string, object, collection, user defined datatype) in its index by using ADD() method and by using count method we will know how many object the ArrayList currently hold. So let’s go for an example on dynamic arrays in both C# and VB.Net.


CLICK HERE to read How to convert ArrayList  to Array.




C# Dynamic Array Example:
using System;
using System.Collections;

public partial class Dynamic_Array : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList Dynamic_List = new ArrayList();
       
        for(int i=0; i<5; i++)
            Dynamic_List.Add(i);

        Dynamic_List.Add("You can put Object/any datatype here !!");

        for (int i = 0; i < Dynamic_List.Count; i++)
            Response.Write("Index " + i.ToString() + ": " + Dynamic_List[i].ToString() + "</br>");
    }
}

VB.Net Dynamic Array Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Dynamic_List As New ArrayList()
        Dim i As Integer

        For i = 0 To 5
            Dynamic_List.Add(i)
        Next i

        Dynamic_List.Add("You can put Object/any datatype here !!")

        For i = 0 To Dynamic_List.Count - 1
            Response.Write("Index " + i.ToString() + ": " + Dynamic_List(i).ToString() + "</br>")
        Next i

    End Sub
End Class

Hope now you can use Dynamic array in asp.net C# VB.Net.

Tuesday, June 15, 2010

VC++ fatal error LNK1104: cannot open file 'Export.def'




Please visit my new Web Site WWW.Codedisplay.com



When you want to create a DLL file to use in C# windows application or from other applications then you may experience the below error:

fatal error

Exception: fatal error LNK1104: cannot open file 'xxx.def'

Reason:
You define the definition file from Project--> Project Properties. But the project won't get the definition file in the project path.

Solution:
Create or copy the definition file into the project root path.

Error: Unable to find an entry point named 'xxx' in DLL 'yyy.dll'




Please visit my new Web Site WWW.Codedisplay.com



To access any DLL file from C# windows application or from other application an entry point is required. Otherwise you will get the below exception:

Entry point not found exception

Unable to find an entry point named 'xxx' in DLL 'yyy.dll'
OR
Entry point not found exception / error.

When you create any DLL file in VC++ from a turbo C program then you must have create a definition file where you will define the DLL entry point. You have to create the Definition file within the root folder. This will not resolve your problem. To resolve the problem go to the Project--> Project Properties and define the definition file in the following way:

define entry point

Hope now you can resolve the problem.

Sunday, June 13, 2010

Make Turbo C DLL to use in C# windows application




Please visit my new Web Site WWW.Codedisplay.com



In some cases of our professional life we need to parse or decode or handle large number of file. As you knew that for IO purpose turbo C is faster than other technologies like dot net or something else. In my cases i need to develop an ASN decoder where i need to decode more than million of files. In such cases i need to develop a ASN decoder. In my cases i have done the following way:

1. Create a Turbo C program which will decode ASN files.
2. Convert the Turbo C program to a DLL to use in C# windows application.
3. After that upload data into the SQL Server/Oracle database.

Here in this article i will explain only how one can create a DLL file created in Turbo C and then use this DLL file in C# windows application. Steps were given below:



1. Create a Turbo C program Like below:
#include<stdio.h>
#include<conio.h>

int ADDs(int num1,int num2)
{
 return num1+num2;
}

int Subtract(int num1,int num2)
{
  return num1-num2;
}

void main()
{
 //printf("%d",ADDs(10,10));
}

2. Now open Visual Studio 2005.
3. Go to File--> New --> Project.
4. Now configure Language= VC++ and from templates select Win32 Project like below:

VC++ Project

5. Now type the name of the DLL and then click on OK.
6. Now click on Next.
7. Select Application Type=DLL like below:

VC++ Application Type

8. Now click Finish.
9. Now write the two function ADDs and Subtract in the following way:

VC++ Application Type

10. Now your VC++ code window will like below:
#include "stdafx.h"


#ifdef _MANAGED
#pragma managed(push, off)
#endif

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{
    return TRUE;
}


int ADDs(int num1,int num2)
{
 return num1+num2;
}

int Subtract(int num1,int num2)
{
  return num1-num2;
}


#ifdef _MANAGED
#pragma managed(pop)
#endif
11. Now we need to create a definition file.
12. Now go to File-->New-->File. You will get below window:

DLL Definition File

13. Save the file as Export.def in the project root folder.
14. Now write the below content in Export.Def file:
LIBRARY "mymath"
EXPORTS
  ADDs
  Subtract

Or

Right cilck on mymath solution. Click Add-->New Item like below:

Def File

15. Now go to the Project--> Project Properties and define the Export.def file in the following way:

Define definition file

16. Now build your project.
17. Go to the debug folder and copy the mymath.dll file into your system32 folder.
18. Now create an C# windows application. Within the form Add two textboxes and one command button.
19. Now under button click event write below sample code:
private void button1_Click(object sender, EventArgs e)
        {
            int a=Adds(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
            MessageBox.Show(a.ToString());
        }
20. Don't forget to import DLL as well as including using System.Runtime.InteropServices; So full code will be:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("mymath.dll")]
        public static extern int Adds(int Num1, int Num2);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int a=Adds(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text));
            MessageBox.Show(a.ToString());
        }
    }
}

21. Now run the project. Hope you will get your desired output.

Tuesday, June 8, 2010

Run-Time Check Failure #2 - Stack around the variable 'hexByte' was corrupted




Please visit my new Web Site WWW.Codedisplay.com



If you are going to develop any game or decoder then you may experience this error. Today when i am developing an ASN decoder for our company i faced the error below:

Run-Time Check Failure #2 - Stack around the variable 'hexByte' was corrupted.

To develop my decoder first i need to develop a turbo C program. Then convert this code into a DLL. When i am calling the dll function from my C# windows application i found this error. The screenshot is given below:

DLL Error

Basically for example this will happen if you are going to write to an invalid address. Mostly this comes from something like this.
char hexByte[5];
hexByte[6] = 'E';

Then when you leave from function scope system will freeing the variable hexbyte then system will prompt this error that the variable is corrupted because you wrote to an invalid address.

So check the variable that is stated in your error message & increase the size of the array will resolve your problem.

Thursday, June 3, 2010

ERROR: Items collection cannot be modified when the DataSource property is set




Please visit my new Web Site WWW.Codedisplay.com



Basically we get this error when we try to add a data into the combobox after binding the combobox by using datasource property. If we use to bind data in this way comboBox1.Items.Add then we didn't get any error. But if we want to add data after binding then we will get below error:

Items collection cannot be modified when the DataSource property is set.



Screenshot is given below:

Combobox Error

Lets try to make this error. After that we will resolve this problem. To make this error first add a form in your project then add a combobox control within this form & run the below code:
private void Form1_Load(object sender, EventArgs e)
        {
            DataTable oTable = new DataTable("Article");

            //Add DataTable column dynamically/run time/on the fly.
            oTable.Columns.Add(new DataColumn("ID", typeof(System.Int64)));
            oTable.Columns.Add(new DataColumn("Title", typeof(System.String)));

            //Add DataTable rows dynamically/run time/on the fly.
            oTable.Rows.Add(1001, "DataTable Engineering");
            oTable.Rows.Add(1002, "Event Calendar");
            oTable.Rows.Add(1003, "Master Detail Data");

            comboBox1.DataSource = oTable;
            comboBox1.DisplayMember = "Title";

            // this line will generate error 
            comboBox1.Items.Insert(0, "Select");
        }


Here you can test by using a database for simplicity i use datatable.

Now solution:
In such type of scenario i always modify the datasource like datatable first. After that i bind this datasource into the combobox. So to resolve this problem my workaround is given below:
private void Form1_Load(object sender, EventArgs e)
        {
            DataTable oTable = new DataTable("Article");

            //Add DataTable column dynamically/run time/on the fly.
            oTable.Columns.Add(new DataColumn("ID", typeof(System.Int64)));
            oTable.Columns.Add(new DataColumn("Title", typeof(System.String)));

            //Add DataTable rows dynamically/run time/on the fly.
            oTable.Rows.Add(1001, "DataTable Engineering");
            oTable.Rows.Add(1002, "Event Calendar");
            oTable.Rows.Add(1003, "Master Detail Data");

            // Use insertAt method to force to enter data
            DataRow oRow = oTable.NewRow();
            oRow["Title"] = "Select";
            oTable.Rows.InsertAt(oRow, 0);


            comboBox1.DataSource = oTable;
            comboBox1.DisplayMember = "Title";
        }

Happy coding.

Sunday, May 30, 2010

Insert bulk data into oracle using SQLLoader in C#




Please visit my new Web Site WWW.Codedisplay.com



Sometimes we need to insert a large volume of data into the Oracle database. Sometimes data comes from comma seperated csv file or from a comma seperated text file. By reading this article you can insert data from both source to oracle. There are mainly two ways to insert bulk data into Oracle:

1. Using Bindarray
2. Using SqlLoader

Here in this article i will explain how one can use to insert bulk data from text file or csv file into oracle
using SQLLoader.

To do that please follow the below steps:

1. Create a folder in your c: drive and named it WorkingFolder.
2. Create a controller file in the WorkingFolder using below code:
LOAD DATA
INFILE DataOut.txt
BADFILE dataFile.bad
APPEND INTO TABLE SASN
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' 
(CDR_Type,Rec_Type)
And name this file by "Ctrl.txt".
3. Now create a text file which contins data like below:
1,2
3,4
5,6
And name this file "DataOut.txt".
4. Now create a sample table in oracle like below:

Oracle Table

5. Now from your c# project run the below sample code:
Process proc = new Process();
            string myCommand = @"CMD.EXE";
            proc.StartInfo = new ProcessStartInfo(myCommand);
            
            //Set up arguments for CMD.EXE
            proc.StartInfo.Arguments = @"/c SQLLDR User/Password@Schema CONTROL=C:\WorkingFolder\Ctrl.txt";

            proc.StartInfo.RedirectStandardOutput = true;

            proc.StartInfo.RedirectStandardError = true;

            proc.StartInfo.UseShellExecute = false;

            proc.StartInfo.WorkingDirectory = @"c:\WorkingFolder\";
            proc.Start();
            proc.WaitForExit();

            if (proc.ExitCode == 0) // Successfully completed
                MessageBox.Show("Successfully Inserted");
            
            else
                MessageBox.Show(proc.StandardError.ReadToEnd());

6. Now run the above code & hope you will get below output:

SQLLoader Output

Sunday, May 16, 2010

How to read hidden field data in GridView Asp.net C#




Please visit my new Web Site WWW.Codedisplay.com



In some cases developers need to collect more data instead of datakeynames. In that cases developers use hidden field to retain those important data. Here in this article i wil show how one can use hidden field to store some important data & how can read those. For simplicity here i use a product table & use ID in a hidden field to read them from server side SelectedIndexChanged event. The product table looks like below:

Product

Now add a page in your project & also add a GridView like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_Hidden.aspx.cs" Inherits="GridView_Hidden" %>

<!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>How to read GridView Hiden Field Data</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
         <HeaderStyle BackColor="Red" Font-Bold="True" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />

         <Columns>
             <asp:CommandField ShowSelectButton="True" />

             <asp:TemplateField HeaderText="Product Name">
             <ItemTemplate>
             <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("ID")%>'></asp:HiddenField>
             <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label>
             </ItemTemplate>
             </asp:TemplateField>

             <asp:BoundField DataField="Description" HeaderText="Description" />
             <asp:BoundField DataField="Color" HeaderText="Color" />
             <asp:BoundField DataField="Size" HeaderText="Size" />


         </Columns>
            <SelectedRowStyle BackColor="Blue" ForeColor="White" />
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Now under SelectedIndexChanged event write the below code to read hidden field value within gridview template column:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = clsDBUtility.GetDataTable("SELECT * FROM PRODUCT");
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;
        Response.Write("Product Id=" + sValue);
    }
Now run the project & will get below like output:

Output

Hope now you can read & use the hidden field vlaue from within a GridView.

Thursday, May 13, 2010

Error: The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator




Please visit my new Web Site WWW.Codedisplay.com



When you google this error you will get a lots of solution. But no one help me to resolve my problem. So i am working on this issue to find out my solution & finally i got a simple problem which i want to share with you. My situation is i have a link server (SQL Server 2008) with my working Sql server 2005. I have created a table in the link server means Sql server 2008 which is given below:

Sql Server Table

And i wrote a sample stored procedure with a dynamic SQL to produce this error like below:
CREATE PROCEDURE SP_Test
@Table_Tail AS VARCHAR(20)
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @STRSQL AS VARCHAR(5000)

 SET @STRSQL = 'DELETE FROM [xxxxx\SQL01].[RA_CTL_SUMMARY].dbo.TBL_IBSPhase2 WHERE EntryDate='''+@Table_Tail+''' 
 AND Prefix=''NOKIA'' '
 EXEC (@STRSQL) 

END

The problem is when i want to run or execute this query i will get the below error:
Msg 306, Level 16, State 1, Line 1
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.

Solution:
In this case the solution is simple. Just change the datatype size of column Prefix MAX to a fixed size will resolved my problem. Means in my scenario i have declared the datatype of Prefix column from VARCHAR(MAX) to VARCHAR(5000).

In your case this may not be the situation so keep googling & try other solutions. This is one of the solution only which i did not get from google.

Tuesday, May 11, 2010

Set alternate table row color using JQuery




Please visit my new Web Site WWW.Codedisplay.com



In many cases we need to represent data in tabular format so that user can easily read data in straightforward way. It will be more helpful for users if we can give or set different row color for alternate rows of the table to distinguish one row from another. To do that i have googled and found some examples. But each example will not consider the header row of the table. I need to color alternate rows except header. So i tried to write a JQuery method which will color alternate rows of a table except considering header row and i want to share with you.







To do the example first create the table and definitely give an id for header rows to distinguish header row in JQuery method like below:
<table>
    <caption>Article History</caption>
    <thead><tr id="Header"><th>Article</th><th>Published</th></tr></thead>
    <tr><td>An introduction to JQuery</td><td>May 01, 2010</td></tr>
    <tr><td>How to set TextBox Value using JQuery</td><td>May 03, 2010</td></tr>    
    <tr><td>How to color Alternate Row</td><td>May 05, 2010</td></tr>    
    <tr><td>How to declare Variable in JQuery</td><td>May 07, 2010</td></tr>    
    <tr><td>What is JQuery $ Symbol</td><td>May 09, 2010</td></tr>        
    </table>

And the JQuery method will be:
<script language="javascript">
            $(document).ready(function() {
                $("caption").css("text-align", "left");
                $('#Header').css("background-color", "Red");
                // You can also add css like:
                $('#Header').addClass('abc');
                $("tr:not(\'#Header\'):even").css("background-color", "Blue");
                $("tr:not(\'#Header\'):odd").css("background-color", "Green");
            });
    </script>

Here i showed how you can apply direct CSS as well as cssclass using JQuery.

The code is self explanatory except filter option. The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements.

Now run the page and hope you will get the below interface:

JQuery alternate row color

Hope it will help you.

How to get set read TextBox value using JQuery




Please visit my new Web Site WWW.Codedisplay.com



As we knew that using javascript to read or get or set textbox value is easy but due to JQuery notation novice developers always make mistakes to read textbox value. Here in this article i will show you how one can get set read textbox value or textbox text using JQuery.









To run the example first add a page in your project. Then add three textboxes and one command button to do sum like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQuery1.aspx.cs" Inherits="jQuery1" %>

<!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>How to read TextBox value using JQuery</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtFirst"></asp:TextBox>
        <asp:TextBox runat="server" ID="txtSecond"></asp:TextBox>
        <asp:Button runat="server" ID="btn" Text="+" />
        <asp:TextBox runat="server" ID="txtSum"></asp:TextBox>
    </div>
    </form>
</body>
</html>

Now add the below JQuery script which will read two number from txtFirst & txtSecond and set the result into third TextBox:
<script language="javascript">
            $(document).ready(function() {          
                $('#btn').click(function() {
                    
                    // Read First number & 2nd Number from TextBox
                    var $nFirstNum = parseInt($('#txtFirst').val())
                    var $nSecondNum = parseInt($('#txtSecond').val())
                    var $nResult = $nFirstNum+$nSecondNum
                    
                    // Set the result into txtSum TextBox
                    $('#txtSum').val($nResult)
                    return false;
                });
            });
    </script>


Now run the page. Hope you will get below interface:
JQuery SUM

Hope now you can read or write value to a TextBox using JQuery easily.

Monday, May 10, 2010

How to declare JQuery variable & What is JQuery $ sign symbol




Please visit my new Web Site WWW.Codedisplay.com



In my first article i have discussed on how to start JQuery in your asp.net application. Here in this article i will explain how one can declare simple JQuery variable as well as object type Jquery variable also i will explain what does it mean by Jquery $ sign.

At first What is variable:
In programming, a variable is a value that can change, depending on conditions or on information passed to the program. Typically, a program consists of instructions that tell the computer what to do and data that the program uses when it is running. The data consists of constants or fixed values that never change and variable values (which are usually initialized to "0" or some default value because the actual values will be supplied by a program's user).

Now declaring a variable in JQuery:
Declarinag a variable in JQuery almost like javascript declaration. See the below example which will use simple variables:
<script language="javascript">
            $(document).ready(function() {          
            var a=10;
            var b=20;
            var c=a+b;
            alert(c);
            });
    </script>    


Now what is Jquery $ sign:
To initialize an object JQuery uses $ symbol. You can use this symbol to pass selector, function, string etc to execute or implement some functionality. You can replace the symbol $ by jquery word which will give you same result. Basically its a notation you have to use to pass a selector.

So the best way of declaring a variable in JQuery based on my first example is:
<script language="javascript">
            $(document).ready(function() {          
            var $a=10;
            var $b=20;
            var $c=$a+$b;
            alert($c);
            });
    </script>    

Object Declaration:
JavaScript supports Object concept very well. We can declare object variable same as javascript. You can create an object using the object literal in JQuery as follows:
<script language="javascript">
        $(document).ready(function() {          
            var Developer = {
               $Name: "Shawpnendu",
               $Experience: 6
            };
            
            //You can write and read properties of an object using the dot notation as follows:
            
            // Read Properties
            
            alert(Developer.$Name)
            
            // Write or set properties
            Developer.$Name="Bikash"
            alert(Developer.$Name)            
        });
    </script>    

Hope this will help you.

Introduction on using JQuery in Asp.net application




Please visit my new Web Site WWW.Codedisplay.com



In a single line jQuery is a fast, lightweight client side library that is CSS3 compliant and supports almost all browsers. The jQuery framework is extensible and very nicely handles DOM manipulations, CSS, AJAX, Events and Animations. By using JQuery you can dramatically reduce your client side code. Jquery code is completely separate from your HTML code. Around the world many JQuery gurus develops handy plugins for you which you can use to boost up user experience while browsing your application. You can easily integrate JQuery with your AJAX application as well as Microsft start to provide intelligence on writing JQuery from VS 2008.

OK now start.

To Start JQuery first visit the JQuery site and download latest JS file.

Now create a project. Add a folder named Script and add the JQuery js file in this folder.

Now open your Default.aspx page and include the JQuery library just after the Title tag within Head section in your page like below:
<script src="Script/jquery.js" type="text/javascript"></script>

Now your application is ready to use JQuery. Ok first we try to write Hello World ! as usual. For this modify your default.aspx page Head tag HTML markup like below:
<head runat="server">
    <title>An introduction to JQuery</title>
    <script src="Script/jquery.js" type="text/javascript"></script>

    <script type="text/javascript"> 

        $(document).ready(function() { 
                alert('Hello World !');
            });
    </script>    
</head>

Now run the project & you will get below output:

JQuery 1

Another example:
Add a button control in your page & run the page & click on the button. You will get Hello World ! message again. To do that modify your default.aspx page Head tag & Body tag HTML markup like below:
<head runat="server">
    <title>Untitled Page</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    
    <script language="javascript">
            $(document).ready(function() {          
                $('#btn').click(function() {
                    alert('Hello World !');
                });
            });
    </script>    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button runat="server" ID="btn" Text="Click Me" />
    </div>
    </form>
</body>

The output will be:

JQuery 2

If you look at the button control HTML you wouldn't get any extra code to implement this click example like javascript. This is the beauty of JQuery which tell us that "Separate javascript code from HTML mark-up".

Now read the documentation from jquery site to enrich yourself and keep in mind that JavaScript is a language whereas jQuery is a library written using JavaScript.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash