Monday, October 27, 2008

Filling Windows Forms ListView with DataTable

If your are not familiar with List visit my blog Windows Forms ListView.

DataTable dt = new DataTable("Shalvin");
DataRow dr;
DataColumn dc;

private void Form1_Load(object sender, EventArgs e)
{
listView1.View = View.Details;

listView1.Columns.Add("Blog", 170);
listView1.Columns.Add("Author", 170);

dc = new DataColumn("Blog");
dt.Columns.Add(dc);

dc = new DataColumn("Author");
dt.Columns.Add(dc);

dr= dt.NewRow();
dr["Blog"] = "http://weblogs.asp.net/Scottgu/";
dr["Author"] = "Scott Guthrie";
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["Blog"] = "DotNetShalvin.blogspot.com";
dr["Author"] = "Shalvin";
dt.Rows.Add(dr);

listView1.Items.Clear();







To make things simple I am creating a DataTable and DataRows by code .Afterward I am iterating through the DataRows collection and adding it into ListView's SubItems collection.


private void Form1_Load(object sender, EventArgs e)
{
..
..
ListViewItem lvbl = new ListViewItem("Add new record");
listView1.Items.Add(lvbl);
}

private void listView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (listView1.FocusedItem.Text.ToString() == "Add new record")
MessageBox.Show("Add new record");
}

















VB .Net

Dim dt As New DataTable("Shalvin")
Dim dr As DataRow
Dim dc As DataColumn

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListView1.View = View.Details
ListView1.Columns.Add("Blog", 170)
ListView1.Columns.Add("Author", 170)

dc = New DataColumn("Blog")
dt.Columns.Add(dc)
dc = New DataColumn("Author")
dt.Columns.Add(dc)

dr = dt.NewRow()
dr("Blog") = "http://weblogs.asp.net/Scottgu/"
dr("Author") = "Scott Guthrie"
dt.Rows.Add(dr)

dr = dt.NewRow()
dr("Blog") = "DotNetShalvin.blogspot.com"
dr("Author") = "Shalvin"
dt.Rows.Add(dr)

For index As Integer = 0 To dt.Rows.Count - 1
Dim dr As DataRow = dt.Rows(index)
Dim lvi As New ListViewItem(dr("Blog").ToString())
ListView1.Items.Add(lvi)
lvi.SubItems.Add(dr("Author"))
Next


Related Blog :
DataTable DataColumn and DataRow (Asp .Net)

DataGridView - Extracting the Contents of Currently Selected Row



FileSystemWatcher Component and Class in WPF and Windows Forms

FileSystemWatcher Component (Class) can be used to monitor file system directories for changes. FileSystemWatcher Class in WPF FileSystemWatcher Class in found in System.IO namespace using System.IO is not added by default in WPF. using System.IO; private void Window_Loaded(object sender, RoutedEventArgs e) { FileSystemWatcher fsw = new FileSystemWatcher(); fsw.Path = @"c:\"; fsw.IncludeSubdirectories = true; fsw.EnableRaisingEvents = true; fsw.Created +=new FileSystemEventHandler(fsw_Created); } private void fsw_Created(object sender, FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " created"); } FileSystemWatcher Component in Windows Forms Add a FileSystemWatcher to the form. Since it is a component it will appear in the component tray. Support if you want to monitor c: and its sub directories for changes, then set the Path property to C:, IncludeSubdirectories to True and EnableRaisingEvents to true. Now you can write event handlers for the FileSystemWatcher Component as follows: private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " created"); } private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e) { MessageBox.Show(e.FullPath + " deleted"); } A better approach would be writing to an event log or a text file. Related blog: DataTable DataColumn and DataRow (Asp.Net)

Sunday, October 26, 2008

LINQ to Sql

I am going to demonstrate LINQ to Sql by writing code.

Support you have a table called Categories in Shalvin database you need to first create a Entity. An Entity is a class that represents a Table or a view in the database.

Create a class as follows:
Set a reference to Data.Linq.

using System.Data.Linq.Mapping;

[Table]
public class Categories
{
[Column(IsPrimaryKey=true, IsDbGenerated=true)]
public int CategoryId { get; set; }

[Column]
public string CategoryName { get; set; }

[Column]
public string Description { get; set; }
}

Each property should have Column Atribute. I am also setting values of IsPrimaryKey and IsDbGenerated for CategoryId column. Editing is possible only if IsPrimaryKey is set to true. IsDbGenerated Indicated that it is an Identity column.


In the asp .net page :

using System.Data.Linq;
protected void Page_Load(object sender, EventArgs e)
{
string ConString = "Integrated Security=sspi;Initial Catalog=Shalvin";
DataContext db = new DataContext(ConString);
var tMovies = db.GetTable<categories>();
GridView1.DataSource = tMovies;
DataBind();
}Now suppose you are interested only in viewing the Categories table with CategoryName 'Confections'.

GridView1.DataSource = tMovies.Where(m => m.CategoryName.Contains("Beverages"));
The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities .

Linq to Sql with Visual Studio Tools

Having seen the internals lets turn our attention to the Visual Studio Support of Linq to Sql.
Here I have started an Empty Visual Studio Project and Added a Linq to Sql Classes from the Add New Item Dialog. I have renamed it AirLines.dbml



On to the design surface it is possible to drag the table from Database Explorer.



That's all I have to do and I am ready to do CRUD operation with the selected tables.

AirLinesDataContext context = new AirLinesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    GridView1.DataSource = context.Locations;

    DropDownList1.DataSource = context.Locations;
    DropDownList1.DataTextField = "LocationName";
    DropDownList1.DataValueField = "LocationId";

    DataBind();
  }
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
  Response.Write(DropDownList1.SelectedValue.ToString());
}

protected void btnInsertLocation_Click(object sender, EventArgs e)
{
  var loc = new Location { LocationName = "London", Latitude =67 };
  context.Locations.InsertOnSubmit(loc);
  context.SubmitChanges();
}


Related Blogs
Linq to Objects
Linq to Xml (Code Snippets)

Wednesday, October 15, 2008

Microsoft Innovation Days Kochi

Learn for free about building reliable, high performance applications with a super-rich user interactivity using Microsoft technologies, such as the Visual Studio 2008, SQL Server 2008, Windows Server 2008, Silverlight 2 RC0 and Internet Explorer 8.

Date: November 6, 2008 (Thursday)

Venue: Taj Residency
Marine Drive, Shanmugham Road
Ernakulam, Cochin 682304

9 am Tea and Registration

9:45 AM Keynote - The magic of Software

Sneak peak into the host of technology innovations that Microsoft is working on - Windows 7, Live platform, Cloud services and many more , accompanied with uber-cool demos.

10:45 AM Next generation web experience with IE 8 and Silverlight
Learn how you can leverage some of the developer features in IE 8 to "light up" your web site and provide a compelling experience to your website users by rendering your data on Silverlight controls.

12:00 PM SQL Server – Optimize your Queries

Lunch Break (1.30 - 2.30)

2:30 PM Partnering with Microsoft
Learn about the various partnering opportunities with Microsoft that will support and enhance your development and marketing efforts.

3:00 PM AJAX - Get it right for your
ASP.NET Applications
Find out how to AJAX Enabling your ASP.NET Applications in the right way and also explore some of the best practices to build a high performance web application. Finally, learn how the new version of ASP.NET improves AJAX enabled web development.

4:30 PM The developer's toolkit for building .Net applications.

Find out the host of tools you can use to analyze and identify performance bottlenecks in your .Net applications. Explores some of the in-built tools that ships with the .NET SDK such as ildasm, gacutil, ngen, fxcop etc and and features in Visual Studio. which will help you develop better, faster, more secure, error free NET applications.

Click here to register

Friday, October 10, 2008

Silverlight 3/Wpf : Adding Controls Dynamicallys

Lets see how to dynamically add controls and attaching event handler to the added control.

Here I am creating an object of button class and adding it into the Grid using the Add method of Grid's Children property.

private void btnAddControl_Click(object sender, RoutedEventArgs e)
{
Button btn = new Button();
btn.Click += new RoutedEventHandler(btn_Click);
btn.Content = "Shalvin";
btn.Width = 75;
btn.Height = 25;
Grid1.Children.Add(btn);
}

private void btn_Click(object sender, RoutedEventArgs e)
{
//MessageBox works only with WPF , Silverlight 3 and not with Silverlight 2
MessageBox.Show("ShalvinPD.blogspot.com");
}

Result

WPF Routed Event

A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

For example if you want a single event handler for the buttons inside a Grid you can define a Routed event as Button.Click = "Grid_Click" inside the Grid as shown in the diagram.









private void Grid_Click(object sender, RoutedEventArgs e)
{
//MessageBox works only with WPF and not Silverlight 2
MessageBox.Show("ShalvinPD.blogspot.com");
}

Wednesday, October 8, 2008

Silverlight 3/WPF Templates

WPF introduces the concept of lookless controls.

Using Templates it is possible to change the appearance of a control. For examples it is possible for a ListBox to contain the Photos of employees instead of the usual List Items.

I am going to demonstrate creating a simple Template whereby a button will appear as a blue rectangle.














Silverlight Tags

<UserControl x:Class="ButtonTemplate.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Height="50" Width="75">
            <Button.Template>
                <ControlTemplate>
                    <Rectangle Fill="LightBlue"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</UserControl>




Result



















As shown in the output the button can respond to click event as expected.

Now lets create an ellipse button.










Result

Monday, October 6, 2008

WPF Styles

Styles are equivalent to CSS in html. Lets see how to create Styles in WPF.Inside the Window Xaml tag add a Window.Resource section.In the Style tag's TagetType you can specify to what type of control you want the style to apply. Using Setters you can specity the Property and and its corresponding value.























Here is the result





















In this example I am setting the Background, Width and Opacity properties for Button. All the buttons in the form will inherit these properties thereby rendering a consistant look and feel.