How to insert data into Database using Silverlight

November 10, 2009

First Create Silverlight application

Start -> Programs -> VS2008 -> File -> New -> Project -> SilverlightApplication -> ByDefault application name is SilverlightApplication1 change name as SilverlightDB

 

Original article from

http://www.codeforasp.net/how-to-insert-data-into-database-using-silverlight.html

Silverlight-solution-explorer
Silverlight-solution-explorer

Step2: Design Registration form in Page.xaml

Silverlight Grid with 8 Rows and 2 Columns using grid RowDefinition and ColumnDefinition

<UserControl xmlns:controls=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit”  x:Class=”SilverlightDB.Page”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

Width=”400″ Height=”300″>

<Border BorderBrush=”Black” BorderThickness=”1″ >

<Grid x:Name=”LayoutRoot” Background=”White” ShowGridLines=”False” >

<Grid.RowDefinitions>

<RowDefinition Height=”35″></RowDefinition>

<RowDefinition Height=”30″></RowDefinition>

<RowDefinition Height=”30″></RowDefinition>

<RowDefinition Height=”30″></RowDefinition>

<RowDefinition Height=”30″></RowDefinition>

<RowDefinition Height=”30″></RowDefinition>

<RowDefinition Height=”40″></RowDefinition>

<RowDefinition Height=”70″></RowDefinition>

</Grid.RowDefinitions>

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”130″></ColumnDefinition>

<ColumnDefinition Width=”270″></ColumnDefinition>

</Grid.ColumnDefinitions>

<StackPanel Grid.Row=”0″ Grid.Column=”0″ Grid.ColumnSpan=”2″ Width=”400″ Background=”Gray” >

<controls:Label  FontSize=”14″ FontWeight=”bold” HorizontalAlignment=”Center”

Content=”Registration Form” Margin=”6,5,-5,5″></controls:Label>

</StackPanel>

<controls:Label Grid.Row=”1″ Grid.Column=”0″ Content=”FirstName” Margin=”10,5,5,5″ HorizontalAlignment=”Center”></controls:Label>

<TextBox Grid.Column=”1″ Grid.Row=”1″ Height=”25″ Width=”150″ HorizontalAlignment=”Left”></TextBox>

<controls:Label Grid.Row=”2″ Grid.Column=”0″ Content=”EmailID” Margin=”10,5,5,5″ HorizontalAlignment=”Center”></controls:Label>

<TextBox Grid.Row=”2″ Grid.Column=”1″ Height=”25″ Width=”150″ HorizontalAlignment=”Left”></TextBox>

<controls:Label Grid.Row=”3″ Grid.Column=”0″ Content=”PhoneNo” Margin=”10,5,5,5″ HorizontalAlignment=”Center”></controls:Label>

<TextBox Grid.Row=”3″ Grid.Column=”1″ Height=”25″ Width=”150″ HorizontalAlignment=”Left”></TextBox>

<controls:Label Grid.Row=”4″ Grid.Column=”0″ Content=”LoginName” Margin=”10,5,5,5″ HorizontalAlignment=”Center”></controls:Label>

<TextBox Grid.Row=”4″ Grid.Column=”1″ Height=”25″ Width=”150″ HorizontalAlignment=”Left”></TextBox>

<controls:Label Grid.Row=”5″ Grid.Column=”0″ Content=”Password” Margin=”10,5,5,5″ HorizontalAlignment=”Center”></controls:Label>

<TextBox Grid.Row=”5″ Grid.Column=”1″ Height=”25″ Width=”150″ HorizontalAlignment=”Left”></TextBox>

<Button Grid.Row=”6″ Grid.Column=”1″ Width=”100″ Height=”25″ HorizontalAlignment=”Left” Content=”Register”></Button>

</Grid>

</Border>

</UserControl>

Run the application

Silverlight-Registration-form
Silverlight-Registration-form

CREATE TABLE [dbo].[Registration](

[registerID] [int] IDENTITY(1,1) NOT NULL,

[FirstName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[EmailID] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[PhoneNo] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[LoginName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

[Password] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,

CONSTRAINT [PK_Registration] PRIMARY KEY CLUSTERED

(

[registerID] ASC

)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

Create Linq to SQL Classes

Right click in SilverlightDB.Web (see above figure)

-> Add -> New Item -> Linq to SQL classes ->

By Default Linq to SQL Classes (DataClasses1.dbml) change its name into Silverlight.dbml

-> Add -> Then it opens dbml Editor click ServerExplorer ->

Then it display Silverlight (database name in list of Databases)

Choose Silverlight

-> Right click choose Modify Connections (Modify ConnectionString by choosing ServerName : your server name

UserName : your username

Password : your password

Select Database: Silverlight

Then Expand Silvelright database to view tables in Server Explorer (View ->ServerExplorer)

silverlight-ServerExplorer
silverlight-ServerExplorer

Drag Registration table into Silverlight.dbml Editor then see Solution Explorer it creates Silverlight.dbml with two files

Silverlight.dbml.layout file

Silverlight.designer.cs file

Silverlight-dbml
Silverlight-dbml

Create WCF Service in Silverlight Project

Right click in SilverlightDB.Web (see above figure)

-> Add -> New Item -> choose Silverlight from Categories -> right side choose

Service-enabled WCF Service

silverlight enabled WCF Service
silverlight enabled WCF Service

Change Name: Service1.svc into Register.svc then click Add Button it generates below code

Register.svc.cs

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.Collections.Generic;

using System.Text;

namespace SilverlightDB.Web

{

[ServiceContract(Namespace = "")]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Register

{

[OperationContract]

public void DoWork()

{

// Add your operation implementation here

return;

}

// Add more operations here and mark them with [OperationContract]

}

}

For inserting data using WCF and Silverlight

namespace SilverlightDB.Web

{

[ServiceContract(Namespace = "")]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Register

{

[OperationContract]

public void DoWork()

{

// Add your operation implementation here

return;

}

// Add more operations here and mark them with [OperationContract]

[OperationContract]

public void InsertData(string firstname,string emailid,string phoneno,string loginuser,

string password)

{

//SilverlightDataContext is Dbml file Silverlight.dbml //(SilverlightDataContext)

SilverlightDataContext db = new SilverlightDataContext();

//From Silverlight.dbml.cs file Registeration(sqlserver name table name row

//  [Table(Name="dbo.Registration")]

//public partial class Registration : INotifyPropertyChanging, INotifyPropertyChanged

//{

//    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

//    private int _registerID;

//    private string _FirstName;

//    private string _EmailID;

//Registration from Silverlight.dbml table name

Registration row = new Registration()

{

FirstName = firstname,

EmailID = emailid,

PhoneNo = phoneno,

LoginName = loginuser,

Password = password

};

// Add the new object to the collection.

db.Registrations.InsertOnSubmit(row);

// Submit the change to the database.

db.SubmitChanges();

}

}

}

Add Web Service Reference to Silverlight Application (Pages like Page.xaml…)

Goto SilverlightDB in Solution Explorer -> choose Referenes -> click Add Service Reference

Add-Service-Reference
Add-Service-Reference

Then the below DailogBox Opens

Service-Reference-Discover
Service-Reference-Discover

Click Discover -> It display all WCF services which Created in Project we created only one WCF service i.e. Register.svc it displays all operations included in Register.svc

First it display Register.svc with expand and Collapse + symbol click (+) symbol . Now it displays Register webservice with expand and collapse click (+) symbol

Now it displays Register in Services and right side it displays Operations.

Operations

  • DO Work
  • Insert Data
Register-WCF-Operations
Register-WCF-Operations

Click Ok then it creates Service Reference all Silverlight Pages (page.xaml…)

It creates ServiceReference to Silverlight Application see below figure.

ServiceReferences
ServiceReferences

Insert Data into SqlServer using Silverlight Xaml file

Now goto Page.xaml (Registration form)

click in Submit Button right click

Click Navigate to Event Handler

<Button Grid.Row=”6″ Grid.Column=”1″ Width=”100″ Height=”25″ HorizontalAlignment=”Left” Content=”Register” Click=”SubmitRegister_Click” ></Button>

using SilverlightDB.ServiceReference1;

private void SubmitRegister_Click(object sender, RoutedEventArgs e)

{

RegisterClient webservice = new RegisterClient();

webservice.InsertDataAsync(txtFirstName.Text, txtEmailID.Text, txtPhoneno.Text, txtLoginName.Text, txtPassword.Text);

}

Explaination:

RegisterClient webservice=new RegisterClient()

Register is WCF service name

Client is ByDefault is Client Service

So Register+Client = RegisterClient

InsertDataAsync

InsertData = WCF service (Register.svc) Operation (Function) is assigned to insert data into database.

Async = ServiceReference to InsertData

So InsertData+Async = InsertDataAsync

Hit F5 to run the application


insert and display data into excel using asp.net

July 23, 2009

Create excel file as Data.xls and change the name of sheet1 to users

in users sheet type ID,Name,Address,Phoneno in first row to inserting data

and for display the data in drag gridview control.

excel

file name: Data.xls

sheet name: users

Step1: In Default.aspx page take four textbox’s(ID,Name,Address,Phoneno) and one submit button

change Textbox ID in Properties

ID textbox =txtID

Name textbox =txtName

Address textbox=txtAddres

Phoneno textbox=txtPhoneno

step2: Connectionstring write below code

“ConnectionString” for for Office 97-2003
string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\lokeshoracle\\data.xls;Extended Properties=Excel 8.0;”;

“ConnectionString” for for Office 2007

string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\excel\\data.xls;Extended Properties=\”Excel 8.0;HDR=YES;\“”;

step3: Displaying excel data in gridview

In Page_load event

Dont forget to use below namespaces

using System.Data;
using System.Data.OleDb;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
string  connectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\lokeshoracle\\data.xls;Extended Properties=Excel 8.0;”;
OleDbConnection objConn = new OleDbConnection(connectionString);

string query = “select * from [users$]“;
OleDbCommand objCmd = new OleDbCommand(query,objConn);

DataSet objDs = new DataSet();
OleDbDataAdapter objDa = new OleDbDataAdapter(objCmd);

objConn.Open();
objDa.Fill(objDs);
objCmd.ExecuteNonQuery();
GridView1.DataSource = objDs;
GridView1.DataBind();
objConn.Close();
}

step4: Inserting the data into excel sheet

protected void btnSubmitExcelData_Click(object sender, EventArgs e)
{
OleDbConnection objConn = new OleDbConnection(connectionString);
//string query = “insert into [users$] values(1,’bbb’,'bbb’,’2345′)”;
string query = “insert into [users$](ID,Name,Address,Phoneno) values(“+txtID.Text+”,’”+txtName.Text+”‘,’”+txtAddress.Text+”‘,’”+txtPhoneno.Text+”‘)”;
OleDbCommand objCmd = new OleDbCommand(query, objConn);

objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
}

Happy coding


multiple silverlight xaml controls in one aspx page

July 18, 2009

XAML page contains one or more elements that control the layout and

behavior of the page.You arrange these elements hierarchically in a

tree.

System.Windows.Application derived class named App with the

associated App.xaml and App.xaml.cs files; as well as a

System.Windows.Controls.UserControl derived class called Page with

the associated Page.xaml and Page.xaml.cs files.

The App class takes care of the initialization and basically you

assign a new instance of your Page class to the App.RootVisual

property and through the power of Silverlight it appears on your

screen. you can set RootVisual as many times you want. So

Application_Startup can be used to call multiple Silverlight

controls.

In this project there are two xaml files and they will be added to

one aspx page(i.e. Default.aspx page)

My Application Name multipleXaml

Xaml Pages are

Page.Xaml
calender.xaml

Page.Xaml Code will look like

<UserControl x:Class=”multipleXaml.Page
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”200″ Height=”200″>
<Grid x:Name=”LayoutRoot” Background=”White”>
<Ellipse  Fill=”Beige”></Ellipse>
</Grid>
</UserControl>

calender.xaml code will look like

<UserControl

xmlns:basics=”clr-namespace:System.Windows.Controls;assembly=System.W

indows.Controls”  x:Class=”multipleXaml.calender
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”200″ Height=”200″>
<Grid x:Name=”LayoutRoot” Background=”White”>
<basics:Calendar></basics:Calendar>
</Grid>
</UserControl>

Remember xaml control names

(multiplexaml.calender remove applicationName multiplexaml. then it remains calender so calender.xaml name is calender)

calender.xaml name is calender

Page.xaml name is Page (multiplexaml.Page)

Note : Before adding this two controls in Default.aspx page you have to modify

App.xaml.cs file modify the code in Application_Startup method. This will call all xaml controls using

initParams

//remember InitParams key name is ControlId using this silverlight controls will display in Default.aspx page. In Default.aspx design code you will observer use of ControlId term in Silverlight control  it look like InitParameters=”ControlId=calender”


<asp:Silverlight ID=”Silverlight1” runat=”server”Height=”200px” Width=”200px” InitParameters=”ControlId=calender”

Source=”~/ClientBin/multipleXaml.xap” MinimumVersion=”2.0.30523″></asp:Silverlight>

code will look like
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();

if (e.InitParams.ContainsKey(“ControlId“))
{

switch (e.InitParams["ControlId"])
{

case “calender”:  //this calls from  calender.xaml page

this.RootVisual = new calender();

break;

case “Page”:

this.RootVisual = new Page();

break;

//add more pages like this
//case “dropdown”:
//    this.RootVisual = new dropdown();
//    break;

}

}
}

Now goto Default.aspx Page Add Two Silverlight control from Toolbox.
(In Toolbox Silverlight Tab name contain Silverlight,Pointer and

MediaPlayer control).
Add ScriptManager above of the Default.aspx Page

Sample Design code look like

Default.aspx Page Design

<form id=”form1″ runat=”server”>
<div>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>
</asp:ScriptManager>
<table align=”center”>
<tr>
<td>
<asp:Silverlight ID=”Silverlight1” runat=”server”

Height=”200px” Width=”200px” InitParameters=”ControlId=calender”

Source=”~/ClientBin/multipleXaml.xap” MinimumVersion=”2.0.30523″>
</asp:Silverlight>

</td>
</tr>
<tr>
<td>
<asp:Label ID=”Label1″ runat=”server”

Text=”Label”></asp:Label>

</td>
</tr>
<tr>
<td>
<asp:Silverlight ID=”Silverlight2” runat=”server”

Height=”200px” Width=”200px” InitParameters=”ControlId=Page”

Source=”~/ClientBin/multipleXaml.xap” MinimumVersion=”2.0.30523″>
</asp:Silverlight>
</td>
</tr>
</table>

</div>
</form>

Now Run the application .In Default.aspx Page ,the Page.Xaml control

and calender.xaml control will appear.

Happy coding


asp.net convert string to date, date to string, string to Int,string to Double,string to Decimal,object to int,object tostring,string to byte array

July 16, 2009

www.codeforasp.net

asp.net convert string to date

string strDate = DateTime.Today.ToString();
DateTime c = DateTime.Parse(strDate);

For TextBox Control: If TextBox contain Calender Date value for date comparisions use below code

DateTime a = DateTime.Parse(TextBox1.Text);

asp.net convert string to integer

string a = “1234″;

int b = Convert.ToInt16(a);
int c = 2;

int d = b + c;

SO string a value is converted to integer and stored in b. for testing i declare int c=2 and i add b and c values
then the result d is integer.

asp.net convert datetime to string

string strDate = DateTime.Today.ToString();

DateTime date = DateTime.Today;
string a = date.ToString(“dd/MM/yyyy”); //result look like 01-12-08
string b = date.ToString(“dd MMM, yyyy”); //result look like 01 Dec, 2008
string c = date.ToString(“dd/MM/yyyy”).Replace(“-”,”/”); // result look like 01/12/2008
string month = date.ToString(“MM”); // result look like month is 12
string alphaMonth = date.ToString(“MMM”); //result look like month is Dec
string fullMonth = date.ToString(“MMMM”); //Result full month name is like December
string day = date.ToString(“dd”); //result look like day is 01
string weekdayName = date.ToString(“ddd”);  //Result look like Wed
string FullweekDayName = date.ToString(“dddd”); //Result look like Wednesday
string shortDate = date.ToShortDateString(); //result is 01-Dec-09
string longDate = date.ToLongDateString(); //result is Wednesday, Dec 01, 2009

asp.net convert object to string

object txtbox;
txtbox = “items”;
string objStr = txtbox.ToString();

asp.net convert object to int

object txtbox;
txtbox = 3;
int objInt =Convert.ToInt16(txtbox);

asp.net convert string to decimal

string a = “1234.34″;
decimal b = decimal.Parse(a);

asp.net convert string to double

string a = “1234.34″;
double b = Convert.ToDouble(a);

Note:

string a = “$52.50″;
double b = Convert.ToDouble(a.Substring(1));

asp.net convert string to byte array

‘ VB.NET to convert a string to a byte array
Public Shared Function StrToByteArray(str As String) As Byte()
Dim encoding As New System.Text.ASCIIEncoding()
Return encoding.GetBytes(str)
End Function ‘StrToByteArray

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

‘ VB.NET to convert a byte array to a string:
Dim dBytes As Byte() = …
Dim str As String
Dim enc As New System.Text.ASCIIEncoding()
str = enc.GetString(dBytes)

// C# to convert a byte array to a string.
byte [] dBytes = …
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);

asp.net convert string to byte array from http://www.chilkatsoft.com/faq/DotNetStrToBytes.html

Thank u


Comparing two dates in Asp.net

July 16, 2009

In this tutorial I compare two dates in asp.net using two textbox controls and two ajax calender controls. You can use

asp.net calender controls instead of ajax calender controls but date formats must be same for both textbox’s date values i.e

(“dd/MM/yyyy” or “MM/dd/yyyy”)

www.codeforasp.net

Date Formats for Ajax CalendarExtender Control

Format=”MMMM d, yyyy”  Result is April 28, 1906

=”dd/MM/yyyy”    Result is 23/11/2008

=”MM/dd/yyyy”    Result is 12/28/2008

=”dd-MMM-yyyy” Result is 23-Mar-2008
Comparing Two dates

If second textbox1(DespatchOrder) date value is less than to first textbox2(OrderTaken) date value then alert box will

display “Check date values”.This TextBox2_TextChanged event is fired when textbox2 is less than textbox1 date value.

Default.aspx Page: When using ajax controls paste script manager in aspx pages top. Check Date Formats in ajax calender
must be in dd/MM/yyyy

Ajax CalendarExtender1 both PopupButtonID=”TextBox1″    and  TargetControlID=”TextBox1″

Ajax CalendarExtender2 both PopupButtonID=”TextBox2″    and  TargetControlID=”TextBox2″

When you click Textbox1 or Textbox2 Calender control will popup you can choose the dates from there
comparedates

<table style=”border: 1px solid #000000; font-family: Arial, Helvetica, sans-serif; font-size: 9pt; background-color:

#E6E6E6″>
<tr>
<td>OrderTaken</td>
<td>
<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<cc1:CalendarExtender ID=”CalendarExtender1″ runat=”server” Format=”dd/MM/yyyy”
PopupButtonID=”TextBox1″ TargetControlID=”TextBox1″>
</cc1:CalendarExtender>

</td>
</tr>

<tr>
<td>
DespatchOrder</td>
<td><asp:TextBox ID=”TextBox2″ runat=”server” AutoPostBack=”True”
ontextchanged=”TextBox2_TextChanged”></asp:TextBox>

<cc1:CalendarExtender ID=”CalendarExtender2″ runat=”server” Format=”dd/MM/yyyy”
PopupButtonID=”TextBox2″ TargetControlID=”TextBox2″ >
</cc1:CalendarExtender>

</td>
</tr>

</table>

Default.aspx.cs code: Double click in TextBox2

protected void TextBox2_TextChanged(object sender, EventArgs e)
{
DateTime a = DateTime.Parse(TextBox1.Text);
DateTime b = DateTime.Parse(TextBox2.Text);

if (a > b)
{
Response.Write(“<script>alert(‘Check date ranges to OrderTaken and OrderDespatch’);</script>”);
TextBox2.Text=”";
}
}

***Now Run the project Enter Textbox1 value as 09-02-2008

TextBox2 value as 02-02-2008

then textbox changed event fires and popup alert message “check date ranges to orderTaken and orderDespatch”

Note: You can write in this format also javascript alert message

Response.Write(“<script language=’javascript’>”);
Response.Write(“alert(‘Please Check date ranges to OrderTaken and OrderDespatch.’);”);
Response.Write(“return false;”);
Response.Write(“<” + “/script>”);

Note:

dd_MMM_yyyyYou can compare date formats like above figure but change the ajax calender control formats i.e Format=”dd-MMM-yyyy”

<cc1:CalendarExtender ID=”CalendarExtender1″ runat=”server” Format=”dd-MMM-yyyy”
PopupButtonID=”TextBox1″ TargetControlID=”TextBox1″>
</cc1:CalendarExtender>

Similarly for calenderExtender2 Format=”dd-MMM-yyyy”

Happy coding


Silverlight TimeUpDown,TimePicker and TimePicker & RangeTimePickerPopup

July 16, 2009

TimeUpDown is a silverlight control. It uses textbox to allow user to input time and time changes by clicking up and down
spinners.

It allows you to write 1123 and it converts to 11:23 Or 8a and converts to 8:00 AM.

Artilce from

http://www.codeforasp.net/silverlight-timeupdowntimepicker-and-timepicker-rangetimepickerpopup.html

properties:

set “value” will display default time as you mentioned in TimeUpDown control i.e 11:00 AM

“Culture” values can be set to specific cultures only, such as en-GB for English/Great Britain,
en-US for English/United States.

set the TimeFormat used to format the string, as either Short, Long or custom

Format =”Long” looks like 8:59:30 AM
Format =”Short” looks like 11:00 AM
Format =”hh:mm” looks like 11:00

sample code

<Grid x:Name=”LayoutRoot” Background=”White” >

<inputToolkit:TimeUpDown Value =”11:00″ Width=”100″ Culture=”en-US” Format=”Long” >
</inputToolkit:TimeUpDown>

</Grid>

TimePickers

TimePicker is a Silverlight control that allows the user to pickup a time through a Popup.

MaxDropDownHeight is the property of TimePickers used to increase or decrease the height of the popup

<Grid x:Name=”LayoutRoot” Background=”White” >

<inputToolkit:TimePicker Culture=”it-IT” Format=”hh.mm” MaxDropDownHeight=”200″ Margin=”0,12,0,0″>

<Grid x:Name=”LayoutRoot” Background=”White” >

TimePicker & RangeTimePickerPopup

TimePicker is a Silverlight control that allows the user to pickup a time through a Popup.
RangeTimePickerPopup Represents a time picker popup that allows choosing time through 3 sliders: Hours, Minutes and seconds.

Sample code

<inputToolkit:TimePicker Culture=”it-IT” Format=”hh.mm” MaxDropDownHeight=”200″ Margin=”0,12,0,0″>

<inputToolkit:TimePicker.Popup>
<inputToolkit:RangeTimePickerPopup></inputToolkit:RangeTimePickerPopup>
</inputToolkit:TimePicker.Popup>

</inputToolkit:TimePicker>


SilvSilverlight Treeview Control and HyperlinkButton

July 15, 2009

In this article Treeview nodes are navigating to other pages using HyperlinkButton using content control property of  silverlight Treeview control.

<Grid x:Name=”LayoutRoot” Background=”White”>

<controls:TreeView BorderBrush=”Black” BorderThickness=”2″ Width=”200″ Background=”Cornsilk”>

<controls:TreeViewItem Header=”Home” IsSelected=”True” IsExpanded=”True”   >

<controls:TreeViewItem Header=”Languages” IsExpanded=”True” >

<ContentControl>
<HyperlinkButton NavigateUri=”http://www.cprogramming.com/tutorial.html”  Content=”C”

TargetName=”_blank”></HyperlinkButton>
</ContentControl>
<ContentControl>
<HyperlinkButton NavigateUri=”http://www.cprogramming.com/tutorial.html” Content=”C++”

TargetName=”_blank”></HyperlinkButton>
</ContentControl>
<ContentControl>
<HyperlinkButton NavigateUri=”http://www.c-sharpcorner.com/” Content=”CSharp” TargetName=”_blank”

></HyperlinkButton>
</ContentControl>

</controls:TreeViewItem>

<controls:TreeViewItem Header=”Web Technologies” IsExpanded=”True”>
<ContentControl>
<HyperlinkButton NavigateUri=”http://www.asp.net/” Content=”Asp.Net”

TargetName=”_blank”></HyperlinkButton>
</ContentControl>

<ContentControl>
<HyperlinkButton NavigateUri=”http://silverlight.net/GetStarted/”  Content=”Silverlight”

TargetName=”_blank”></HyperlinkButton>
</ContentControl>

<ContentControl>
<HyperlinkButton NavigateUri=”http://www.asp.net/mvc/” Content=”MVC” TargetName=”_blank”

></HyperlinkButton>
</ContentControl>
</controls:TreeViewItem>

</controls:TreeViewItem>

</controls:TreeView>

</Grid>


Silverlight Treeview Control

July 15, 2009

Treeview is used to display hierarchical data in a tree structure that has item,the items can expand and collapse. It has three nodes.
They are Root,Parent and Leaf.

Root – A root node is a node that has no parent node. It has one or        more child nodes.

Parent – A node that has a parent node and one or more child nodes

Leaf – A node that has no child nodes

Silverlight Toolkit also contain Treeview control as an asp.net Toolkit control.

Sample Code for Silverligh Treeview

<Grid x:Name=”LayoutRoot” Background=”White” >

<controls:TreeView BorderBrush=”Black” BorderThickness=”2″ Width=”200″ Background=”Cornsilk”>

<controls:TreeViewItem Header=”Home” IsSelected=”True” IsExpanded=”True”   >

<controls:TreeViewItem Header=”Languages” IsExpanded=”True” >
<controls:TreeViewItem Header=”C “></controls:TreeViewItem>
<controls:TreeViewItem Header=”C++”></controls:TreeViewItem>
<controls:TreeViewItem Header=”Pascal”></controls:TreeViewItem>
</controls:TreeViewItem>

<controls:TreeViewItem Header=”Web Technologies” IsExpanded=”True”>
<controls:TreeViewItem Header=”Asp.net”></controls:TreeViewItem>
<controls:TreeViewItem Header=”Silverlight”></controls:TreeViewItem>
<controls:TreeViewItem Header=”MVC”></controls:TreeViewItem>
</controls:TreeViewItem>

</controls:TreeViewItem>

</controls:TreeView>

</Grid>


Binding XML data to Gridview Template Field

July 15, 2009

With ASP.NET data binding, you can bind any server control to simple properties, collections, expressions and/or methods. When you use data binding, you have more flexibility when you use data from a database or other means.

Article from

http://www.codeforasp.net/binding-xml-data-to-gridview-template-field.html
Data binding essentials
<%# %> Syntax
ASP.NET introduces a new declarative syntax, <%# %>. This syntax is the basis for using data binding in an .aspx page. All data binding expressions must be contained within these characters.

let us start Binding XML data to Gridview Template Field using dataset

ReadXml method is used to fill it with schema and data.

using order.xml file to bind the data into gridview template field

<?xml version=”1.0″?>
<orderReport>
<report>
<orderCode>1234</orderCode>
<Date>21321</Date>
<Location>dada</Location>
<Content>asad</Content>
<Count>12</Count>
</report>
<report>
<orderCode>1002</orderCode>
<Date>09-02-2009</Date>
<Location>chennai</Location>
<Content>plasma</Content>
<Count>5</Count>
</report>
<report>
<orderCode>1003</orderCode>
<Date>06-03-2008</Date>
<Location>pune</Location>
<Content>Bikes</Content>
<Count>10</Count>
</report>
</orderReport>

step1: Open visual studio –> File –> New –> Website –>choose visual studio template asp.net website–>ok

step2: Drag the Gridview control into default.aspx page
keep Gridview AutoGeneratecolumns property is false

step3: goto gridview Tasks –> click Edit columns.. –> choose TemplateField –>click add button (templateField is added to

gridview) –>click OK  see below figures

gridviewTemplate field

gridviewTemplate field

Gridview edit Template field

Gridview edit Template field

now again goto Gridview Tasks click Edit Templates see below figure

gridview itemtemplate

gridview itemtemplate

step4: now add table with 1 row and 4 columns inside item template of gridview add four labels to that columns of the table
inside item template.

gridview edit databinding

gridview edit databinding

step5: Bind xml values (ordercode,location,content binding 3 column fields only out of 5 you can bind 5 fields ). To bind
values  (  see above figure click label edit DataBindings)

gridview binding value

gridview binding value

similarly bind location field, content field. There are three labels in my gridview

label1 is binded as Eval(“orderCode”)

label2 is binded as Eval(“Loaction”)

label3 is binded as Eval(“Content”)

above binding names must be same as xml data i.e

<report>
<orderCode>1234</orderCode> // this orderCode is Eval(“orderCode”)
<Date>21321</Date>
<Location>dada</Location> //this Location is Eval(“Location”)
<Content>asad</Content> //this content is Eval(“Content”)
<Count>12</Count>
</report>

step 6: After binding all values click End Template Editing.

gridview EndTemplate Field

gridview EndTemplate Field

now see the design view of gridview

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID=”Label1″ runat=”server” Text=’<%# Eval(“orderCode”) %>’></asp:Label>
</td>
<td>
<asp:Label ID=”Label2″ runat=”server” Text=’<%# Eval(“Location”) %>’></asp:Label>
</td>
<td>
<asp:Label ID=”Label3″ runat=”server” Text=’<%# Eval(“Content”) %>’></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Write the code to display the data

Note:1) my xml file name is order.xml it doesn’t contain any     folders.so give the path as Server.MapPath(“order.xml”)

2) If the order.xml inside the folder name of orderDetails then         change the path as

Server.MapPath(“orderDetails/order.xml”)

sample code look like in Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
txtDateOfReport.Text = DateTime.Now.ToShortDateString();
DataSet objDs = new DataSet();

//it does not contain any folder
objDs.ReadXml(Server.MapPath(“order.xml”));

//Inside orderDetails is foldername contain order.xml file
//objDs.ReadXml(Server.MapPath(“orderDetails/order.xml”));

GridView1.DataSource = objDs.Tables[0].DefaultView;
GridView1.DataBind();

}


display XML data into Gridview

July 15, 2009

I explained already how to insert form data into xml file in previous

article you can click this link to navigate to that article.

http://lokeshbasana.wordpress.com/2009/07/14/adding-form-data-to-xml-file-using-asp-net/
Now i am going to explain how to display xml data into gridview using

dataset

Reads XML schema and data into the DataSet using the specified

System.IO.Stream.

ReadXml method is used to fill it with schema and data.

Steps  to display xml data into gridview
step1: Open visual studio –> File –> New –> Website –>choose

visual studio template asp.net website–>ok
step2: order.xml file data

<?xml version=”1.0″?>
<orderReport>

<report>
<orderCode>1234</orderCode>
<Date>21321</Date>
<Location>dada</Location>
<Content>asad</Content>
<Count>12</Count>
</report>

<report>
<orderCode>1002</orderCode>
<Date>09-02-2009</Date>
<Location>chennai</Location>
<Content>plasma</Content>
<Count>5</Count>
</report>

<report>
<orderCode>1003</orderCode>
<Date>06-03-2008</Date>
<Location>pune</Location>
<Content>Bikes</Content>
<Count>10</Count>
</report>

</orderReport>

step3: Drag the Gridview control into default.aspx page then write

the code in page_load event to display xml data into gridview.

order
Note:1) my xml file name is order.xml it doesn’t

contain any    folders.so give the path as

Server.MapPath(“order.xml”)

2) If the order.xml inside the folder name of

orderDetails then change the path as

Server.MapPath(“orderDetails/order.xml”)

sample code look like in Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
txtDateOfReport.Text = DateTime.Now.ToShortDateString();
DataSet objDs = new DataSet();

//it does not contain any folder
objDs.ReadXml(Server.MapPath(“order.xml”));

//Inside orderDetails is foldername contain order.xml file
//objDs.ReadXml(Server.MapPath(“orderDetails/order.xml”));

GridView1.DataSource = objDs;
GridView1.DataBind();
}


Follow

Get every new post delivered to your Inbox.