Search This Blog

Wednesday, December 22, 2010

How to bind or populate Dropdownlist from XML file

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:



<Products>
<Product>
<ID>1ID>
<Name>Product 1Name>
Product>
<Product>
<ID>2ID>
<Name> Product 2Name>
Product>
<Product>
<ID>3ID>
<Name> Product 3Name>
Product>
<Product>
<ID>4ID>
<Name> Product 4Name>
Product>
<Product>
<ID>5ID>
<Name> Product 5Name>
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.

Maintaining Scroll Position after Asp.Net Page PostBack

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'.

<%@ Page Language="C#" CodeFile="Default.aspx.cs" MaintainScrollPositionOnPostback="true" Inherits="_Default" %>

How to use optional parameter in SQL server SP

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:

view sourceprint?
01 ALTER procedure Optional_Procedur

02 @Name varchar(200)=null,

03 @Age int=null

04 As

05 BEGIN

06 if @Name is not null

07 print 'Your Name Is '+@Name

08 if @Age is not null

09 print 'Your Age '+Convert(varchar(3),@Age)

10 END

Now you can call the SP in many different ways like:

view sourceprint?
1 exec Optional_Procedur 'Shawpnendu'

2 print '-----------------------------'

3 exec Optional_Procedur 'Shawpnendu',32

4 print '-----------------------------'

5 exec Optional_Procedur @Name='Shawpnendu'

6 print '-----------------------------'

7 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.

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

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



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Updating GridView using AJAXtitle>
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.

Create Autocomplete TextBox using AJAX in Asp.net 3.5

Asp.net 3.5 ease our life. As you knew that Microsoft community published a series of controls named ASP.NET AJAX Control Toolkt. Which you can download from http://www.asp.net/ajax . The AutoCompleteExtender is one of them. You can use this AutoCompleteExtender in your page to make an autocomplete textbox within just few minutes. You can't imagine how much its easy. In this AJAX tutorial i will show you how one can create Autocomplete TextBox using AJAX in ASP.NET 3.5. The Autocomplete TextBox provides user a nice & cool experience while entering data. Let in your page one of the TextBox is used to enter referrer name. You knew that to the referrer name is a tedious job for yur application user. So you can incorporate autocomplete facilty to give your user best UI experience.

To make an Autocomplete Textbox first create a project. Then opne the default.aspx page in design view. Add ScriptManager , TextBox , Autocomplete Extender from toolbox. Now your HTML markup will be:



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

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 id="Head1" runat="server">
<title>Ajax Autocomplete Extender Tutorialtitle>
head>

<body>
<form id="form1" runat="server">
<div>

<asp:ScriptManager ID="ScriptManager1" runat="server">asp:ScriptManager>

<asp:Label runat="server" ID="lblReferrerName" Text="Referrer: ">asp:Label>

<asp:TextBox ID="txtName" runat="server">asp:TextBox>

<cc1:AutoCompleteExtender
ID="AutoCompleteExtender1" runat="server" TargetControlID="txtName"
MinimumPrefixLength="2" CompletionInterval="10" EnableCaching="true" CompletionSetCount="3"
UseContextKey="True" ServiceMethod="GetCompletionList">
cc1:AutoCompleteExtender>

div>
form>
body>
html>

Don't confuse for ServiceMethod="GetCompletionList" line from the above code. I will show you how you can create webservice method for Autocomplete Extender. Move your mouse on the TextBox. Then from TextBox control smart tag, select the Add AutoComplete page method option from the provided menu.

After that you will found that a webservice method will be added in your default.aspx.cs page named GetCompletionList. Now you need to modify this method to return your expected set of data. Now look at my code from below.

using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
// Try to use parameterized inline query/sp to protect sql injection
SqlCommand cmd = new SqlCommand("SELECT TOP "+count+" Name FROM tblAgent WHERE Name LIKE '"+prefixText+"%'", conn);
SqlDataReader oReader;
conn.Open();
List CompletionSet = new List();
oReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (oReader.Read())
CompletionSet.Add(oReader["Name"].ToString());
return CompletionSet.ToArray();
}
}


Don't forget to add the namespace using System.Collections.Generic; 







Friday, October 29, 2010

Display Sum Total in the Footer of the GridView Control


Introduction

In this article, we will see how to display the sum total of a column in the footer of the GridView control using Visual Studio 2005.

For the purpose of this article, we will use the Products Table from the Northwind Database and the GridView control for data binding. The GridView control will display the data and SqlDataSource is supplied in the web.config file as shown in Listing 1.

Listing 1
<connectionStrings> <add name="DummyDB"   connectionString="Server=localhost;Integrated  Security=True;Database=NorthWind;Persist,   Security Info=True" providerName="System.Data.SqlClient"/> </connectionStrings>
 
By default, the GridView's Showfooter property is set to false. We'll change it to true. As we are calculating the field UnitPrice, we'll use TemplateField's ItemTemplate to display UnitPrice and FooterTemplate to display the total.

<asp:GridView ID="GridView1"   ShowFooter="true" DataKeyNames="ProductId"   AutoGenerateColumns="false" runat="server"   DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="Productid" HeaderText="Product Id" /> <asp:BoundField DataField="ProductName" FooterText="Total" HeaderText="Product Name" /> <asp:TemplateField HeaderText="Unit Price" FooterStyle-Font-Bold="True"> <ItemTemplate>   <%# GetUnitPrice(decimal.Parse(Eval("UnitPrice").ToString())).ToString("N2") %> </ItemTemplate> <FooterTemplate>   <%# GetTotal().ToString("N2") %> </FooterTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server"  ConnectionString="<%$ ConnectionStrings:DummyDB %>" SelectCommand="Select * from Products"> </asp:SqlDataSource>

Finally, we'll use Helper functions named GetUnitPrice and GetTotal to display the UnitPrice in the ItemTemplate and Total in the FooterTemplate. For instance, for each row of the GridView, a price value is passed to the GetUnitPrice function returning variable Price.
decimal TotalUnitPrice; 
decimal GetUnitPrice(decimal Price)  
{     
TotalUnitPrice += Price;    
return Price; 
decimal GetTotal() 
{    
return TotalUnitPrice; 
}

Thursday, October 28, 2010

Master\Detail with CollapsiblePanelExtender and edit detail with HoverMenuExtender using GridView

Performance Notes:
You'll notice performance issue with sample. The returns actually for many reasons such as the dependency javascript files that will be downloaded for both CollapsiblePanelExtender and HoverMenuExtender. Beside the usage of Nested UpdatePanels.

Nested UpdatePanels with Nested GridViews:
I had to work with Nested UpdatePanels this time. It is just on Parent root UpdatePanel, and many child UpdatePanel underneath it. Below is a demonstration code for the structure of the Nested UpdatePanels with Nested GridViews



<asp:SqlDataSource ID="sqlDsCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
        SelectCommand="SELECT [Customers].[CustomerID], [Customers].[CompanyName], [Customers].[Address] FROM [Customers] INNER JOIN [Orders] ON [Customers].[CustomerID]=[Orders].[CustomerID]&#13;&#10;Group By [Customers].[CustomerID], [Customers].[CompanyName], [Customers].[Address]"
        ProviderName="<%$ ConnectionStrings:Northwind.ProviderName %>"></asp:SqlDataSource>




<asp:UpdatePanel ID="pnlUpdate"                           UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server">


<Triggers>


<asp:AsyncPostBackTrigger ControlID="gvCustomers" ventName="PageIndexChanged" />


</Triggers>


<ContentTemplate>


<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False" DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">


<Columns>


<asp:TemplateField>


<ItemTemplate>


<asp:Panel CssClass="group" ID="pnlCustomer" runat="server">


<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"


Style="margin-right: 5px;" runat="server" />


<span class="header"><%#Eval("CompanyName")%><%#Eval ("Address") %></span>


</asp:Panel>


<asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"                                                        SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate], [CustomerID] FROM [Orders] WHERE ([CustomerID] = @CustomerID)"


UpdateCommand="UPDATE [Orders] SET [Freight] = @Freight WHERE [OrderID] = @OrderID"


DeleteCommand="DELETE FROM [Orders] WHERE [OrderID] = @OrderID">


<SelectParameters>


<asp:Parameter Name="CustomerID" Type="String" DefaultValue="" />


</SelectParameters>


<UpdateParameters>


<asp:ControlParameter Name="OrderID" Type="Int32" ControlID="gvOrders" PropertyName="SelectedValue" />


</UpdateParameters>


</asp:SqlDataSource>


<asp:Panel Style="margin-left: 20px; margin-right: 20px;" ID="pnlOrders" runat="server">


<asp:UpdatePanel ID="pnlUpdateOrders" UpdateMode="Conditional" runat="server">


<ContentTemplate>


<asp:GridView ID="gvOrders" AutoGenerateColumns="False" DataKeyNames="OrderID" CssClass="grid" DataSourceID="sqlDsOrders"


runat="server" OnRowCreated="gvOrders_RowCreated"


OnRowEditing="gvOrders_RowEditing" OnRowCommand="gvOrders_RowCommand">


<RowStyle CssClass="row" />                                                                    <AlternatingRowStyle CssClass="altrow" />


<Columns>


<asp:TemplateField ItemStyle-CssClass="rownum">


<ItemTemplate>


<%# Container.DataItemIndex + 1 %>


</ItemTemplate>


<ItemStyle CssClass="rownum" />


</asp:TemplateField>


<asp:BoundField HeaderText="Order ID" DataField="OrderID"


ItemStyle-Width="80px" ReadOnly="true" >


<ItemStyle Width="80px" />


</asp:BoundField>


<asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}" ItemStyle-Width="100px" ReadOnly="true" >


<ItemStyle Width="100px" />


</asp:BoundField>


<asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"


ItemStyle-Width="110px" ReadOnly="true" >


<ItemStyle Width="110px" />


</asp:BoundField>


<asp:TemplateField HeaderText="Freight">


<ItemTemplate>


<asp:Label ID="lblFreight" runat="server" Text='<%# Bind("Freight", "{0:N2}") %>'></asp:Label>


</ItemTemplate>


<EditItemTemplate>


<asp:TextBox ID="txtFreight" runat="server" Text='<%# Bind("Freight", "{0:N2}") %>' Width="50px"></asp:TextBox></EditItemTemplate>


<ItemStyle HorizontalAlign="Right" Width="50px" />


</asp:TemplateField>


<asp:BoundField DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"


HeaderText="Date Shipped" ItemStyle-Width="100px" ReadOnly="true">


<ItemStyle Width="100px" />


</asp:BoundField>


<asp:TemplateField HeaderStyle-Width="0px" ItemStyle-Width="0px"


ShowHeader="false">


<ItemTemplate>


<asp:Panel ID="popupMenu" runat="server" Style="display: none">


<div style="border: 1px outset white; padding: 2px;">


<div>


<asp:LinkButton ID="lnkButtonEdit" runat="server"


CommandArgument='<%#Eval("CustomerID")%>' CommandName="Edit" Text="Edit" />


</div>


<div>


<asp:LinkButton ID="lnkButtonDelete" runat="server" Enabled="false"


CommandArgument='<%#Eval("CustomerID")%>' CommandName="Delete" Text="Delete" />


</div>


</div>


</asp:Panel>


<ajaxToolkit:HoverMenuExtender ID="hoverMenu" runat="server"


HoverCssClass="popupHover" PopDelay="300" PopupControlID="PopupMenu"


PopupPosition="Right" TargetControlID="PopupMenu" />


</ItemTemplate>


<EditItemTemplate>


<asp:Panel ID="popupMenu" runat="server">


<div style="border: 1px outset white; padding: 2px;">


<div>


<asp:LinkButton ID="lnkButtonUpdate" runat="server"


CommandArgument='<%#Eval("CustomerID")%>' CommandName="Update" Text="Update" />


</div>


<div>


<asp:LinkButton ID="lnkButtonCancel" runat="server"


CommandArgument='<%#Eval("CustomerID")%>' CommandName="Cancel" Text="Cancel" />


</div>


</div>


</asp:Panel>


<ajaxToolkit:HoverMenuExtender ID="hoverMenu" runat="server"


HoverCssClass="popupHover" PopDelay="300" PopupControlID="PopupMenu"


PopupPosition="Right" TargetControlID="PopupMenu" />


</EditItemTemplate>


<HeaderStyle Width="0px" />


<ItemStyle Width="0px" />


</asp:TemplateField>


</Columns>


</asp:GridView>


</ContentTemplate>


</asp:UpdatePanel>


</asp:Panel>


<ajaxToolkit:CollapsiblePanelExtender ID="cpe" runat="Server" TargetControlID="pnlOrders" CollapsedSize="0" Collapsed="True" ExpandControlID="pnlCustomer" CollapseControlID="pnlCustomer"


AutoCollapse="False" AutoExpand="False" ScrollContents="false" ImageControlID="imgCollapsible" ExpandedImage="~/Assets/img/minus.png" CollapsedImage="~/Assets/img/plus.png" ExpandDirection="Vertical" />


</ItemTemplate>


</asp:TemplateField>


</Columns>


</asp:GridView>


</ContentTemplate>


</asp:UpdatePanel>

Few things to note here. The Parent Panel "pnlUpdateParent" UpdateMode is set to Conditional, and ChildrenAsTriggers is set to false. This is very important, because the Children GridViews will raise postback triggers, and that will cause the whole UpdatePanel to be updated and I don't want that. I just want the child GridView that caused the postback to be updated, while the parent GridView remain silent.
Next you'll notice Triggers tag. Yes, I wanted the Parent UpdatePanel to be only updated when the Parent GridView raises PageIndexChanged Event. that means only upon paging.

Of course the "sqlDsOrders" SqlDataSource has update and delete statement defined. All columns in this GridView are read only except one column. I didn't show them here to save the size of this post. As you can see I declared 3 Event Handlers here:
  • OnRowCreated: used to initialize HoverMenuExtender.
  • OnRowEditing: used to specifying current editing row.
  • OnRowComman: used to specify select parameter value of the SqlDataSource.
It worth to mention that OnRowComman event will be fired and executed every time any command is triggered. And will be fired first and before any other command event fired.


CodeBehind:


using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Text;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxControlToolkit;

public partial class _Default : System.Web.UI.Page
{
    protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            SqlDataSource ctrl = e.Row.FindControl("sqlDsOrders") as SqlDataSource;
            if (ctrl != null && e.Row.DataItem != null)
            {
                ctrl.SelectParameters["CustomerID"].DefaultValue = ((DataRowView)e.Row.DataItem)["CustomerID"].ToString();
            }
        }
    }

    protected void gvOrders_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HoverMenuExtender hoveMenu = (HoverMenuExtender)e.Row.FindControl("hoverMenu");
            e.Row.ID = e.Row.RowIndex.ToString();
            hoveMenu.TargetControlID = e.Row.ID;
        }
    }
    protected void gvOrders_RowCommand(object s, GridViewCommandEventArgs e)
    {
        //CustomerID is stored as event Commend Argument
        string customerId = (string)e.CommandArgument;
        GridView orders = (GridView)s;
        Control parent = orders.Parent.Parent;
        //Find SqlDataSource
        SqlDataSource src = (SqlDataSource)parent.FindControl("sqlDsOrders");
        //Set select parameter value.
        src.SelectParameters[0].DefaultValue = customerId;
    }
    protected void gvOrders_RowEditing(object s, GridViewEditEventArgs e)
    {
        GridView orders = (GridView)s;
        orders.EditIndex = e.NewEditIndex;
        orders.DataBind();
    }
}