Thursday, April 22, 2010

Runtime Add Dynamic DropdownList And Handle SelectedIndexChanged Event in ASP.NET C# VB.NET




Please visit my new Web Site https://coderstechzone.com



In most of the cases developers need to add dynamic controls in asp.net application using code behind or runtime. Here in this article I will explain how one can add dynamically Asp.Net Server side DropdownList control in runtime and assign or handle SelectedIndexChanged event in asp.net using C# and VB.NET. Most of the developers claims that dynamic controls loose data after postback. But if you run this example program you will not face the problem. Don't wrap up the codes under page_laod event within not ispostback condition.

If you run the below example code and select any item from dynamically created DropdownList then you will get the below interface:
Dynamic DropdownList

To add a asp.net server side DropdownList control when page is loaded, we need to write the below code segment under page_Load Event:
C# Code:
protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList ComboBox = new DropDownList();
        ComboBox.ID = "ComboBox";
        ComboBox.AutoPostBack = true;

        ComboBox.Items.Add(new ListItem("Year: 2010", "2010"));
        ComboBox.Items.Add(new ListItem("Year: 2011", "2011"));
        ComboBox.Items.Add(new ListItem("Year: 2012", "2012"));
        ComboBox.Items.Add(new ListItem("Year: 2013", "2013"));
        ComboBox.Items.Add(new ListItem("Year: 2014", "2014"));

        ComboBox.SelectedIndexChanged += new EventHandler(Dynamic_Method);

        this.form1.Controls.Add(ComboBox);
    }

Then add the below handler function:
private void Dynamic_Method(object sender, EventArgs e)
    {
        //Response.Write(((DropDownList)sender).SelectedIndex.ToString());
        //Response.Write(Request.Form["ComboBox"]);
        DropDownList ComboBox=(DropDownList)sender;
        string sSTR = "";
        sSTR = "</br>Selected Index: " + ComboBox.SelectedIndex.ToString();
        sSTR += "</br>Selected Item: " + ComboBox.SelectedItem.Text.ToString();
        sSTR += "</br>Selected Value: " + ComboBox.SelectedItem.Value.ToString();

        Label lbl = new Label();
        lbl.Text = sSTR;
        this.form1.Controls.Add(lbl);
    }

Note: If you want to read DropdownList selectedvalue from other control postback like button control then you can read the above dynamically created DropdownList selectedvalue in the following way:
Response.Write(Request.Form["ComboBox"]);

VB.Net Code:
Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim ComboBox As DropDownList = CType(sender, DropDownList)
        Dim sSTR As String = ""
        sSTR = "</br>Selected Index: " + ComboBox.SelectedIndex.ToString()
        sSTR += "</br>Selected Item: " + ComboBox.SelectedItem.Text.ToString()
        sSTR += "</br>Selected Value: " + ComboBox.SelectedItem.Value.ToString()

        Dim lbl As Label = New Label()
        lbl.Text = sSTR
        Me.form1.Controls.Add(lbl)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ComboBox As DropDownList = New DropDownList()
        ComboBox.ID = "ComboBox"
        ComboBox.AutoPostBack = True

        ComboBox.Items.Add(New ListItem("Year: 2010", "2010"))
        ComboBox.Items.Add(New ListItem("Year: 2011", "2011"))
        ComboBox.Items.Add(New ListItem("Year: 2012", "2012"))
        ComboBox.Items.Add(New ListItem("Year: 2013", "2013"))
        ComboBox.Items.Add(New ListItem("Year: 2014", "2014"))

        AddHandler ComboBox.SelectedIndexChanged, AddressOf Dynamic_Method

        Me.form1.Controls.Add(ComboBox)
    End Sub

Hope now you can add runtime dynamically DropdownList control and also handle its all type of event using above code sample or example.

Tuesday, April 20, 2010

Runtime Dynamically Creating Bound and Template Columns in GridView using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In some complex scenarios developers need to create runtime GridView dynamically. So obviously developers need to create dynamic columns for dynamic gridviews. Here in this article I will explain how one can develop or implement runtime dynamically create bound column as well as template column of a GridView control and also how to bind data into the dynamically created GridView. For simplicity here i use a datatable but you can bind data from database as well. Here I also showed how developers can write dynamic event handler for dynamically created button within the template column. The output will be:
Dynamic GridView

Creating bound column is easier than template column because if you want to add dynamic template column in your GridView then you must implement ITemplate interface. When you instantiate the implemented object then it will automatically call the "InstantiateIn" method. To implement my example first add a class in your project and named it "TemplateHandler". Then copy the code sample:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class TemplateHandler : ITemplate
{
    void ITemplate.InstantiateIn(Control container)
    {
        Button  cmd= new Button();
        cmd.ID = "cmd";
        cmd.Text = "HI";
        cmd.Click += new EventHandler(Dynamic_Method);
        container.Controls.Add(cmd);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        ((Button)sender).Text = "Hellooooo";
    }
}

Now add a page in your project & copy the below codes under page_load event:
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("FirstName");
        dt.Columns.Add("LastName");
        dt.Columns.Add("Age", typeof(System.Int32));

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

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


        GridView gv = new GridView();
        gv.AutoGenerateColumns = false;

        BoundField nameColumn = new BoundField();
        nameColumn.DataField = "FirstName";
        nameColumn.HeaderText = "First Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "LastName";
        nameColumn.HeaderText = "Last Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "Age";
        nameColumn.HeaderText = "Age";
        gv.Columns.Add(nameColumn);

        // Here is template column portion
        TemplateField TmpCol = new TemplateField();
        TmpCol.HeaderText = "Click Me";
        gv.Columns.Add(TmpCol);
        TmpCol.ItemTemplate = new TemplateHandler();        

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

        Form.Controls.Add(gv);
    }

Now run the page & click on the button that i have added in a template column will say you "Helloooo".

Here i showed an example how one can create runtime gridview with bound & template column. Experiment it & hope you will achieve your client target.

Sort Sorting GridView control Manually in Asp.net C#




Please visit my new Web Site https://coderstechzone.com



Asp.net SqlDataSource control ease our lives because if you are using SqlDataSource control to bind a GridView control then no need to sorting gridview or paging gridview control since you will achieve it automatically. But if you are using different datasource like Datatable, DataSet then you need to GridView sorting manually. Here in this article I will show you how you can develop GridView Sorting easily. One thing keep in mind that When you need to sort a GridView then each time you have to bind the GridView with data.

So you have two way to hold data:
1. You can read data from database each time
2. You can store data within viewstate or cache

Here I am using asp.net cache since you knew that viewstate will increase the page response time. Ok lets start. Add a page in your project then add a GridView on it. Now from GridView properties set the AllowSorting=true. Now in your each bind column set the sortexpression like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand" HeaderText="Brand Name" SortExpression="Brand"/>
             <asp:BoundField DataField="Category" HeaderText="Category Name" SortExpression="Category" />
             <asp:BoundField DataField="Product" HeaderText="Product Name" SortExpression="Product"/>
         </Columns>
        </asp:GridView>
* SortExpression must be same as DataField property.


Now in page_load method follow my below sample code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT B.Name Brand,C.Name Category, " +
                    "P.Name Product FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";


            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["dt"] = dt;
            ViewState["Column_Name"] = "Brand";
            ViewState["Sort_Order"] = "ASC";
        }
    }

From here you can change your query according to your base table. Now add the Sorting event of your gridview and write the below code:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == ViewState["Column_Name"].ToString())
        {
            if (ViewState["Sort_Order"].ToString() == "ASC")
                RebindData(e.SortExpression, "DESC");
            else
                RebindData(e.SortExpression, "ASC");
        }
        else
            RebindData(e.SortExpression, "ASC");
    }
If you look at the code you found that here I am using a method named RebindData. The code for this method is given below:
private void RebindData(string sColimnName,string sSortOrder)
    {
        DataTable dt=(DataTable)Cache["dt"];
        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["Column_Name"] = sColimnName;
        ViewState["Sort_Order"] = sSortOrder;
    }

Code Explanation:
Here if you look at my bind query in page_load event then you found that Brand column already sorted in ascending order thats why I have stored the Brand column name & sortorder, so that if user click again on Brand column then i need to sort the column in descending order but if user click on other column then i need to sort that column in ascending order. Hope now you can understand the logic why I use two viewstate variables ViewState["Column_Name"] and ViewState["Sort_Order"]. Basically those two variables is used to remeber user last action.

Now its your turn to make a generic sorting class for your project.

Monday, April 19, 2010

Get all running Sql Server instances name within network using Asp.Net C# vB.Net




Please visit my new Web Site https://coderstechzone.com



Basically who did sql server operational job in any organization sometimes requires to get all running sql server instances name. Here in this asp.net C# VB.Net article i will give you a simple code snippet how you can achieve this. After running my sample code you will get all running sql server instances in your Local Area Network (LAN)/Network even from your local PC like below:

Sql Server Instances name

To run the below code sample just add a page in your project & add a GridView control. Then under page_load event write the below code sample:

C# complete Code:
using System;
using System.Data;
using System.Data.Sql;

public partial class SQL_Insances : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlDataSourceEnumerator SqlEnumerator;
            SqlEnumerator = SqlDataSourceEnumerator.Instance;
            DataTable dTable = SqlEnumerator.GetDataSources();
            GridView1.DataSource = dTable;
            GridView1.DataBind();
        }
    }
}
VB.Net Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (IsPostBack=False) Then
            Dim SqlEnumerator As System.Data.Sql.SqlDataSourceEnumerator
            SqlEnumerator = System.Data.Sql.SqlDataSourceEnumerator.Instance
            Dim dTable As System.Data.DataTable
            dTable = SqlEnumerator.GetDataSources()
            GridView1.DataSource = dTable
            GridView1.DataBind()
        End If
    End Sub

Sunday, April 18, 2010

How to bind Menu control with XML file in Asp.net C# VB.Net




Please visit my new Web Site https://coderstechzone.com



Now developers uses Asp.Net Menu Control as a navigation control. Using this control one can build the navigation system of a website very dynamically. Simply by using this menu control you can create Even complex navigation. It gives us a lot of inbuilt feature like collapse completely or expanded completely. You can also make a navigation down to any level. This Menu Control is very useful when you need to develop dynamic menus. One can also customize the look and feel by defining the properties of the control as well as by CSS.

You can bind the menu control with datasources like SiteMapDataSource and XMLDataSource. Here in this asp.net C# VB.Net article or tutorial i will explain how to bind menu control with a xml file. Its a very useful feature specially for complex dynamic links because you can manage a XML file to organize links easily by the help of XMLDataSource.

To start this Asp.net code example add an aspx page into your project and follow the below steps:
1. Add an XML file into project and give the name "MenuXMLFile.xml". Copy and paste the below code into the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<Articles>
  <Menu text="Asp.Net" url="asparticles.aspx">
    <SubMenu text="GridView" url="GridView.aspx">
        <SubMenu text="GridView Article 1" url="Gv1.aspx"></SubMenu>
        <SubMenu text="GridView Article 2" url="Gv2.aspx"></SubMenu>
        <SubMenu text="GridView Article 3" url="Gv3.aspx"></SubMenu>
        <SubMenu text="GridView Article 4" url="Gv4.aspx"></SubMenu>
        <SubMenu text="GridView Article 5" url="Gv5.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="Ajax" url="Ajax.aspx">
      <SubMenu text="Ajax Article 1" url="Ajax1.aspx"></SubMenu>
      <SubMenu text="Ajax Article 2" url="Ajax2.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="TreeView" url="GridView.aspx">
      <SubMenu text="Getting Started" url="Started.aspx">
        <SubMenu text="TreeView Article 1" url="TV1.aspx"></SubMenu>
        <SubMenu text="TreeView Article 2" url="TV2.aspx"></SubMenu>
        <SubMenu text="TreeView Article 3" url="TV3.aspx"></SubMenu>
        <SubMenu text="TreeView Article 4" url="TV4.aspx"></SubMenu>
        <SubMenu text="TreeView Article 5" url="TV5.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Complex" url="Complex.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="Menu Control" url="GridView.aspx">
        <SubMenu text="Menu 1" url="M1.aspx"></SubMenu>
        <SubMenu text="Menu 2" url="M2.aspx"></SubMenu>
        <SubMenu text="Menu 3" url="M3.aspx"></SubMenu>
        <SubMenu text="Menu 4" url="M4.aspx"></SubMenu>
        <SubMenu text="Menu 5" url="M5.aspx"></SubMenu>
    </SubMenu>
  </Menu>
  <Menu text="Javascript" url="Javascript.aspx">
    <SubMenu text="Javascript Article 1" url="java1.aspx"></SubMenu>
    <SubMenu text="Javascript Article 2" url="java2.aspx"></SubMenu>
  </Menu>
  <Menu text="Sql Server" url="sqlserver.aspx">
    <SubMenu text="Sql Server Article 1" url="SQ1.aspx"></SubMenu>
    <SubMenu text="Sql Server Article 2" url="SQ2.aspx"></SubMenu>
  </Menu>
</Articles>
2. Place a XMLDataSource on to the page from toolbox.
3. From XMLDataSource smart menu click on Configure Datasource.
4. From here click on browse button & select the XML file that you have created few minutes ago. Sample screenshot is given below:

5. Now add a Menu Control into the page.
6. Right click on menu control & go to the properties.
7. From properties set the DataSourceID to the XMLDataSource like below:

8. Again from properties menu click on DataBindings collection & set the navigateurlfield as well as textfield for both Menu & Submenu like below:


Now your HTML markup code should be:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Menu_XML.aspx.cs" Inherits="Menu_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 introduction on How to use Asp.net Menu Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label runat="server" ID="lbl" Font-Bold="true" Font-Underline="true">How to use Asp.net Menu Control</asp:Label>
        <br />
        <br />
        <asp:Menu ID="Menu1" runat="server" DataSourceID="XmlDataSource1" MaximumDynamicDisplayLevels="4">
        <DataBindings>
            <asp:MenuItemBinding DataMember="Menu" TextField="text" ValueField="text" NavigateUrlField="url" />
            <asp:MenuItemBinding DataMember="SubMenu" NavigateUrlField="url" TextField="text" ValueField="text" />
        </DataBindings>
        </asp:Menu>
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/MenuXMLFile.xml"></asp:XmlDataSource>
    </div>
    </form>
</body>
</html>

Now run the project, hope you will get below output:
asp.net menu control

GridView paging manually in Asp.net C#




Please visit my new Web Site https://coderstechzone.com



GridView paging will be required when data volume is higher. If you are using SqlDataSource control to bind a gridview control then no need to paging gridview because you will achieve it automatically. But if you use different datasource then you need to do mannual paging. To enable paging in gridview control at first set the AllowPaging="true" and also define the page size by PageSize="3". In asp.net paging is too much easy. You just need to set the NewPageIndex on the PageIndexChanging event. The ultimate output of my below example looks like:
GridView Paging 1

To do the paging just add a page in your project then add a gridview control on it like below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>
        </asp:GridView>
Now under page load event first bind the data with the gridview and then cache the datasource which we will use to rebind when page index change. Sample code is given below:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt=clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }
    }
Now under gridview PageIndexChanging event write the below code:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = (DataTable)Cache["Data"];
        GridView1.DataBind();
    }
Now run the project, hope you will get paging enabled gridview.

Note: Gridview control gives us PagerSettings tag to enrich look & feel for paging navigation. By using this PagerSettings tag you can navigate from one page to another by image or text instead of default number. To use images as your navigation just use FirstPageImageUrl, LastPageImageUrl, NextPageImageUrl, PreviousPageImageUrl properties.

Now modify your gridview control like below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>

         <PagerSettings 
            Position="Bottom" 
            Mode="NextPreviousFirstLast" 
            FirstPageText="First" 
            LastPageText="Last" 
            NextPageText="Next" 
            PreviousPageText="Prev"
             />
       
        </asp:GridView>
Now you will get below output:
GridView paging 2

Keep experimenting on PagerSettings tag to give the user different look and feel. Later i will discuss on efficient paging. Until then TC.

Saturday, April 17, 2010

How to bind XML file in a TreeView control using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



By using Asp.net TreeView control we can give enhanced UI experience to the user. We can specially use TreeView control to display hierarchical data like MLM tree, Sitemap. We can bind data into the TreeView control from database self referencial table as well as from a XML file. Here in this article or tutorial i am going to explain how one can bind XML data into a TreeView control as well as we will cover how to use asp.net TreeView control means its also an introduction or an introductory article to use asp.net TreeView Control. To do that please follow the below steps:

1. Add an aspx page in your project.
2. Add a XML file in your project and name this file as "ComputerItems.xml". The sample XML file is geven below:




<?xml version="1.0" encoding="utf-8" ?>
<Computer>
  
  <Item Name="Motherboard">
    <Option Value="Intel"></Option>
    <Option Value="Asus"></Option>
    <Option Value="Xbit"></Option>
  </Item>
  <Item Name="Memory">
    <Option Value="128mb"></Option>
    <Option Value="256mb"></Option>
    <Option Value="512mb"></Option>
  </Item>
  <Item Name="Harddrive">
    <Option Value="40gb"></Option>
    <Option Value="80gb"></Option>
    <Option Value="100gb"></Option>
  </Item>
  <Item Name="Soundcard">
    <Option Value="Asus"></Option>
    <Option Value="Vaio"></Option>
    <Option Value="Creative"></Option>
  </Item>

</Computer>
3. Open the aspx page in design view and drag a XMLDataSource into the page.
4. Cilck on the XMLDataSource smart menu and browse to bind the XML file like below:
XML DataSource
5. Now drag a TreeView Control and drop it into your page.
6. From TreeView Control smart menu set the XMLDataSource as DataSource like below:
Tree Datasource
7. Now from TreeView Control smart menu click on Edit TreeNode Databindings to set the XML file Item and Option value like below:
TreeView Node Binding
TreeView Value  Binding

Now your HTML marup code looks like:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TreeView_XML.aspx.cs" Inherits="TreeView_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>How to use TreeView control in ASP.NET 2.0 3.5</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label runat="server" ID="lbl" Font-Bold="true" Font-Underline="true">An introduction to TreeView conrol</asp:Label>
        <br />
        <br />
        <asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1">
            <DataBindings>
                <asp:TreeNodeBinding DataMember="Item" ValueField="Name" />
                <asp:TreeNodeBinding DataMember="Option" ValueField="Value" />
            </DataBindings>
        </asp:TreeView>
    </div>
        <br />
        <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/ComputerItems.xml">
        </asp:XmlDataSource>
    </form>
</body>
</html>
Now run the project and hope you will get below interface:
XML DataBinding
Ok thats it. Now you can bind any XML file as a datasource of a TreeView Control.

Thursday, April 15, 2010

How to pass set Crystal Report Parameter value from asp.net c# in runtime




Please visit my new Web Site https://coderstechzone.com



When you design a crystal report most of the time you need to use crstal report parameter specially to design report header. Like you are going to ouptut a report which contains a ceratin date data or may date range data. SO that you need to write the date range or date to specify the report data date. In this scenario you need to use Crystal report parameter because the data you will bind, may or may not contain the date or date range. User select a date or date range from front end & you will filter those data to bind the report as well as you need to set the date or date range value to report header by sending the date or date range to crystal report parameter. Here i will show you only how you can set one or more or multiple crystal report parameter from asp.net C# page in the runtime.

To know how to bind data please read the below url:
Runtime dynamically bind data into a crystal report using Asp.net C#



Please follow the steps below:
1. Add a crystal report in your project.
2. From Field Explorer right click on Prameter Fields node & click on New.
Create parameter
3. Define the parameter name & Datatype.
Define parameter
4. Drag & Drop the parameter into your report
Drag Drop parameter
5. Now Add an aspx page into your project & set the datasource & parameter value in the following way:
protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("username");
        dt.Columns.Add("useremail");
        dt.Columns.Add("mobile");

        DataRow oItem = dt.NewRow();
        oItem[0] = "Shawpnendu Bikash Maloroy";
        oItem[1] = "shawpnendu@gmail.com";
        oItem[2] = "+8801711080648";

        dt.Rows.Add(oItem);

        ReportDocument _rdTransactionDetails=new ReportDocument();
        string reportPath = Server.MapPath("rptusers.rpt");
        _rdTransactionDetails.Load(reportPath);
        _rdTransactionDetails.SetDataSource(dt);
        
 // Set the parameter value from here
 _rdTransactionDetails.SetParameterValue("date", DateTime.Now);
        CrystalReportViewer1.ReportSource = _rdTransactionDetails;
    }

Please note that "set the parameter value into the report after binding data". Otherwise you will get a prompt to enter data.

Now run the project & check that the report shows the date that you send from aspx page in runtime:
Crystal Report

Get the Time Difference Between Two Date Time in ASP.NET C# VB.Net




Please visit my new Web Site https://coderstechzone.com



In some cases ASP.NET C# VB.Net developers need to find out Time Difference or timediff method or timediff function to get the time between two Time. Here in this article i will show you how you can achieve this:













C# Code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DateTime dtFrom;
            DateTime dtTo;
            string sFrom = "10:35:00";
            string sTo = "12:50:00";
            if (DateTime.TryParse(sFrom, out dtFrom) && DateTime.TryParse(sTo, out dtTo))
            {
                TimeSpan tSpan = dtTo - dtFrom;
                int nDay = tSpan.Days;
                int nHour = tSpan.Hours;
                int nMin = tSpan.Minutes;
                int nSec = tSpan.Seconds;
                string sTimeDiff = nDay.ToString("00") + ":" + nHour.ToString("00") + ":" + nMin.ToString("00") + ":" + nSec.ToString("00");
                Response.Write(sTimeDiff); //output format 00:02:15:00
            } 
        }
    }

VB.Net Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (IsPostBack=False) Then
            Dim dtFrom As DateTime
            Dim dtTo As DateTime
            Dim sFrom As String = "10:35:00"
            Dim sTo As String = "12:50:00"
            If DateTime.TryParse(sFrom, dtFrom) AndAlso DateTime.TryParse(sTo, dtTo) Then
                Dim tSpan As TimeSpan = dtTo - dtFrom
                Dim nDay As Integer = tSpan.Days
                Dim nHour As Integer = tSpan.Hours
                Dim nMin As Integer = tSpan.Minutes
                Dim nSec As Integer = tSpan.Seconds
                Dim sTimeDiff As String = (nDay.ToString("00") & ":") + ((nHour.ToString("00") & ":") + nMin.ToString("00") & ":") + nSec.ToString("00")
                Response.Write(sTimeDiff) 'output format 00:02:15:00
            End If
        End If
    End Sub

Hope now you can get Time Difference between two DateTime or Date Time.

Best way to pass multiple query string value from one page to another page with Response.Redirect method




Please visit my new Web Site https://coderstechzone.com



In most of the cases developers need to pass more than one or multiple query string value from one page to another page. Here in this example i will show you how one can pass multiple values from one page to another page in an efficient way. Let I have a product row and want to send product data from one page to another page so the code will looks like:










protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string sName = "Tibbet";
            string sBrand = "Kohinoor";
            string sDescription = "For menz only";
            Response.Redirect(string.Format("Default.aspx?qs1={0}&qs2={1}&qs3={2}", sName, sBrand, sDescription));
        }
    }
From second page we can read the value like:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if ((Request.QueryString["qs1"] != null && Request.QueryString["qs2"] != null) && Request.QueryString["qs3"] != null)
            {
                string sName = Request.QueryString["qs1"];
                string sBrand = Request.QueryString["qs2"];
                string sDescription = Request.QueryString["qs3"];
                Response.Write(sName+"</br>");
                Response.Write(sBrand + "</br>");
                Response.Write(sDescription);
            }
        }
    }

Further Reading:
Ways to Pass data from one page to another page

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack




Please visit my new Web Site https://coderstechzone.com



Error:
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Reason/Root Cause:
When we call Response.Redirect("") to redirect an aspx page to another aspx page from try/catch block in asp.net code, you will receive the above error.










Sample error code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                // Your other code or logic here
                Response.Redirect("Your Redirect URL");
            }
            catch (Exception ex)
            {
                Response.Redirect("Your Custom Error Page URL");
            }
        }
    }

Solution:
Keep in mind that when you use Response.Redirect or Server.Transfer within try block then use the overload method of Response.Redirect() in the below way will resolve your problem.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                // Your other code or logic here
                Response.Redirect("Your Redirect URL", false);
            }
            catch (Exception ex)
            {
                Response.Redirect("Your Custom Error Page URL");
            }
        }
    }

By setting the second bollean argument of Response.Redirect to false will resolve your problem. On the other hand you can send the redirection code outside of try block.


For more details regarding this error:
ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

Tuesday, April 13, 2010

Runtime Add Dynamic Button And Handle Click Event in ASP.NET C# VB.NET




Please visit my new Web Site https://coderstechzone.com



In most of the cases developers need to add dynamic controls in asp.net application using code behind or runtime. Here in this article i will explain how one can add dynamic Asp.Net Server side Button in runtime and assign or handle click event in asp.net using C# and VB.NET.

To add a asp.net server side button control when page is loaded. We need to write the below code segment under page_Load Event:









C#.Net:
protected void Page_Load(object sender, EventArgs e)
    {
        Button cmd = new Button();
        cmd.Text = "Click Me";
        this.form1.Controls.Add(cmd);
        cmd.Click += new EventHandler(Dynamic_Method);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        Response.Write("You have clicked at: "+DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
    }

VB.Net:
Private Sub Dynamic_Method(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Response.Write("You have clicked at: " + DateTime.Now)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cmd As New Button
        cmd.ID = "BOTON"
        cmd.Text = "Click Me"
        AddHandler cmd.Click, AddressOf Dynamic_Method
        Form.Controls.Add(cmd)
    End Sub

Error: Cannot delete file because it's being used by another person or program




Please visit my new Web Site https://coderstechzone.com



Sometimes you may getting the error when attempting to delete a file which is used by another program or user. In this case you can not rename,move or delete this file or folder.

The error like:
Cannot remove folder xxxxxx: It is being used by another person or program.Close any programs that might be using the file and try again.

And the screen like below:
Error Cannot remove folder

Solution:
1. Try to findout which program have a chance to use this file/folder close it and then try to remove this folder or file.

2. Wait a few minutes & then refresh the window & then try to delete because sometimes Windows or the program using the file may still be closing.

3. Open the task manager click on Applications tab & check does any program uses this file or not? If found any then close it & try again.

4. Go to the processes tab & try to find does any process lock this folder or file? If found then close it and try again. In my cases most of the times i found this problem like let i have a process named abc.exe. After getting this error i close ABC.exe so in the Application tab i didnot found ABC.Exe. But in the processes tab i found abc.exe is still running even you closed earlier. So check it from your end.

5. Close all explorer & window & open files then try again.

6. Restart the PC & try again.

7. If still doesnot resolve or rebooting is not possible(if server) then use the thirdparty software to remove this file or folder named Unlocker.

How to import data from Excel file to Oracle table using toad




Please visit my new Web Site https://coderstechzone.com



In some cases developers need to import excel file date into a oracle table. Here in this article i will explain step by step how one can import excel data into oracle table using TOAD.

The following are the steps to follow import data from Excel sheet to a Oracle Table:

First the Table must exist with the same or equal number of colums as that in the excell sheet.
Now from TOAD go to:
1. Database-->Import-->Table Data
2. Select the proper schema and Table name where data should be inserted
3. Click "Execute Wizard" and specify the type of file to be imported
4. Select "Excel File (.xls)" and click next
5. Give the path of the file, and again click next
6. Finally click execute..

Now your Excel sheet data will be transferred or imported into the oracle table.

Monday, April 12, 2010

Add to Favorites (IE) / Bookmark (Mozilla Firefox, Opera) Page Javascript




Please visit my new Web Site https://coderstechzone.com



Developers basically use shortcut command to add a page into favorite list or bookmark list but most of the users does not know how they can add an important page into their favorite list or bookmark list. Thats why if developer add a bookmark link or add to favorite link on important pages so that users can easily bookmark the page. Here in this article i will explain how one can add favorites link or bookmark link in a page using cross browser javascript code. My example will work on Internet explorer, Opera and Mozilla Firefox like below:
Opera_Mozilla Firefox, Internet explorer IE

To implement my example code first add a aspxa page into your project then under HTML head tag add the below javascript method to bookmark or add to favorites:
<script type="text/javascript">
        function Add_Bookmark_Favorite(url,title) 
        {
         if (window.sidebar) 
         { // Mozilla Firefox Bookmark
             //Make sure "Load this bookmark in the sidebar is deselected
          window.sidebar.addPanel(title, url,"");
          return false;
         } 
         else if( window.external ) 
         { // IE Favorites
          window.external.AddFavorite( url, title); 
          return false;
         }
         else if(window.opera && window.print) 
         { // Opera Bookmark
                return !addToFav(url,title)
            }
        }
    </script>

Now add the below link into your asp.net aspx page like below:
<a href="" title="" rel="sidebar" onclick="return Add_Bookmark_Favorite(location.href, document.title);">Bookmark / Add to Favorites</a>

Now run the page and click on the "Bookmark / Add to Favorites" link will popup a window to bookmark this page.

Sunday, April 11, 2010

Ajax to update GridView after certain interval using Asp.net C#




Please visit my new Web Site https://coderstechzone.com



In most of the cases like Dashboard developers often need to update GridView data after certain interval. In this Asp.Net article i am going to discuss Updating GridView using AJAX. To do that first create a new aspx page in your project. Then drag and drop the below controls within the page.

1. ScriptManager
2. UpdatePanel
3. GridView
4. Timer







Now your aspx HTML markup looks like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Update_Gridview.aspx.cs" Inherits="Update_Gridview" %>

<!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>Updating GridView using AJAX</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
            
         <asp:GridView ID="GridView_Products" runat="server" AutoGenerateColumns="False" 
            Width="100%" Font-Names="tahoma" >
        <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
        <RowStyle BackColor="Gray" />
        <AlternatingRowStyle BackColor="LightGray" />
        <SelectedRowStyle BackColor="Pink" ForeColor="White" Font-Bold="true" />
        <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:BoundField DataField="Color" HeaderText="Color" />
        <asp:BoundField DataField="Size" HeaderText="Size" />
        <asp:CommandField ShowSelectButton="True" />
        </Columns>
        </asp:GridView>    
                <asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick">
                </asp:Timer>
          </ContentTemplate>

        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>
Now right click on Timer control from design view. Click on event. Select Tick event and click twice to go to the code behind. Now within the Timer Tick event just bind the GridView data. Its automatically refresh the GridView after certain interval which you can mention in the Interval properties of the Timer control in seconds. The code sample is given below:
protected void Timer1_Tick(object sender, EventArgs e)
    {
        GridView_Products.DataSource = clsDbUtility.ExecuteQuery("Select * FROM Product");
        GridView_Products.DataBind();
    }
Now insert data from another page and check back your GridView that it has been refreshed. Hope it will help you.
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