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;