-->

Friday, September 6, 2013

How to Bind ListBox with List: WPF

According to the previous post we don’t need to define the items first. Means the source having the items to be bind with listbox. In the XAML define a listbox with some common properties you want as height, width and etc. Don’t forget the name property, because it will be used to assign itemsSource for this control.

<ListBox Name="listBox" Width="200"/>

Create a list of type string and add some items with Add() method of list. I have added the same items as in grid resources.
List<string> strList = new List<string>();
strList.Add("London");
strList.Add("Italy");
strList.Add("California");
strList.Add("France");
listBox.ItemsSource = strList;

Just run the code and the same window will be shown with a listbox containing above four items.

Binding of Listbox with C# List: WPF

Listbox have a property selectedIndex which is used to get or set the selected index of the control. To select an item by default we can use this property as:

listBox.SelectedIndex = 2;

Write the above line of code just below the c# code, and California will be selected.

How to Bind ListBox with XAML Grid Resource: WPF

In the previous article, we have learnt about the listbox and some of the properties of listbox. Resources provide a way to reuse the objects and values by other controllers in the code. As we created a grid resource in the combobox binding, that resource can be used here easily.

Just review the grid resource written as below, where type indicates the type of values defined in it, and the key name will be used to bind other control through it.
<Grid.Resources>          
<x:ArrayExtension Type="{ x:Type sys:String}" x:Key="cmbPlacesSource">
<sys:String>London</sys:String>
<sys:String>Italy</sys:String>
<sys:String>California</sys:String>
<sys:String>France</sys:String>
</x:ArrayExtension>
</Grid.Resources>

Now add a listbox and use its itemsSource property. This property is used to get or set a collection used to generate the content of itemscontrol.
<ListBox Name=”listBox” Width="200"
ItemsSource="{StaticResource cmbPlacesSource}">
</ListBox>

This will show the above items in this listbox as shown in following diagram.

Listbox binding with grid resource: wpf

As the items increases or height decreases, this control will use scroller to view the extra items. Let me set height of above listbox to 30 and lookout the output.

Listbox binding with grid resource plus scrolling: WPF

We can get the selected item’s value from the selection changed event of this control. Write the following code in selection Changed event of listbox
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedValue = listBox.SelectedItem.ToString();
MessageBox.Show(selectedValue);
}

It will show a message, containing the selected item, each time when the selection changed of the listbox control.
Select an Item in listbox binding WPF

How to Access drive information in c#

Using The DriveInfo Class

The DriveInfo class provides access to information related to a drive, such as space availabe on a drive, total storage space of the drive and drive name. The DriveInfo class can also be used to query the format of a drive, such as NTFS or FAT and type of the drive, such as fixed, CD-ROM, or removable. This class throws an exception if a drive is currently not ready. For example, if we want to get information of a CD-ROM that does not contain a CD in it, The DriveInfo class will throw an exception. We can avoid such exceptions by using the IsReady property of the DriveInfo class. If the DriveInfo property returns true, we can access a drive without an exception.
In previous example we have been accessed Logical drives of the system. See previous image

How to access drive of the system

Now in this example we will access Logic drive information such as drive type , drive size and free space of the drive. So first we take four label control to the design window after that handle comboBox1_SelectedIndexChanged event in the program.

Complete code


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] str = Directory.GetLogicalDrives();
            foreach (string item in str)
            {
                comboBox1.Items.Add(item);

            }

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string drive = comboBox1.SelectedItem.ToString();
                label1.Text = "you have Selected Drive " + drive;
                DriveInfo info = new DriveInfo(drive);
                label2.Text = "Drive Type " + info.DriveType.ToString();
                label3.Text = "Free space on drive " + info.AvailableFreeSpace.ToString();
                label4.Text = "Total Size " + info.TotalSize.ToString();



            }
            catch (Exception exp)
            {

                label1.Text = exp.Message;

            }
        }
    }
}


Output
How to Access drive information in c#

How to access system Drives in C#

The Directory class exposes static methods to create , move and enumerate directories and subdirectories.
GetLogicalDrives : Retrieves the name of the logical drives on this computer in the form "<drive letter>:\"

How to access system drives in WebApplication



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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="GetLogical Drives" OnClick="Button1_Click" />
        <br />
        <br />
        <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    </div>
    </form>
</body>
</html>

CodeBehind page

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] str = Directory.GetLogicalDrives();
        foreach (string item in str)
        {
            DropDownList1.Items.Add(item);
        }
    }
}

Output of the program is

How to access system Drives in asp.net

How to access system drives in Window Application

form design for How to access system Drives in C#



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] str = Directory.GetLogicalDrives();
            foreach (string item in str)
            {
                comboBox1.Items.Add(item);

            }

        }
    }
}


Output

How to access system Drives in C#

Display List of Items using ListBox Control: WPF

ListBox control is used to represent a list of items and select a single or some of the items from these. Most often when we have to opt user to select an item from the list of items, then listbox is used.

In WPF this control is somewhat different from the list box of windows forms. It have some properties to be used most often in programming.
  • DataContext: used to specify the source having list of data, through which it will bind. It may be a binding source or an IList.
  • DisplayMemberPath: indicates the name of an object contained in datasource. Specifies what object will be shown to the user.
  • SelectedValue: get or set the selected value from the list of items.
  • SelectedValuePath: used to specify the selected value from the binding source.
  • SelectedIndex: get or set the index of selected value.
  • SelectedItem: indicates the item which is selected.
The following XAML code will create a listbox with three items and none of them is selected.
<ListBox >
<ListBoxItem>first Item</ListBoxItem>
<ListBoxItem>second Item</ListBoxItem>
<ListBoxItem>third Item</ListBoxItem>
</ListBox>

To select an item, set IsSelected property to true. The above XAML code will show a listbox having three items as shown in following image:

ListBox control introduction WPF

The same listbox can also be generated using the following line of code:
<ListBox >
<ListBoxItem>first Item</ListBoxItem>
<ListBoxItem>second Item</ListBoxItem>
<ListBoxItem>third Item</ListBoxItem>
</ListBox>

The listbox can also formatted using its properties like background, foreground and etc. That is how we created a listbox from XAML code.

Thursday, September 5, 2013

Uses of Label Control in WPF

The most usable control in any entry form, details form or any other forms in programming. The textbox is an input control but, on the running mode the label control will notify the user to which value is to be inserted in the relative textbox.


Look out the following entry form in WPF

Entry form showing use of labels: WPF

In the above image the three textboxes are used to input values, but in which order. The respective label will tell us to enter which values in which textbox. The label control which will show a name and some specified width and height is:
<Label>
<Label.Content>Name</Label.Content>
<Label.Height>40</Label.Height>
<Label.Width>100</Label.Width>
</Label>

The above code, when run, will show a text “Name” as in above image. Label control can easily be formatted using its properties like Border Brush, Background, Foreground and etc.

We can easily set an image in label control by using the following line of code:
<Label>
<Label.Background>
<ImageBrush ImageSource="source of image"></ImageBrush>
</Label.Background>
</Label>

That is how we use label control and set image as a background of that label control.

Image Control in WPF

An image can be shown using Microsoft photo viewer, Microsoft Paint or any photo viewing software in windows operating system. But in programming we have to create that from the drawing. If we want to show existing picture then we have to use an in-built control i.e. image control.

Image control is used to display an existing image in WPF programming. The image may be of type bmp, gif, jpg and etc. I have copied an image in my project’s root directory and show that using the below line of code:


<Image Name="imageControl">
<Image.Source>wall.jpg</Image.Source>
</Image>

When we run this project it will show a window containing the image like below:

WPF image control without width and height

It will cover all the space provided by default. We can fix this image to the specified location of the fix height and width. The following code will change it of height 200 and width 200.
<Image Name="imageControl" >
<Image.Source>wall.jpg</Image.Source>
<Image.Height>200</Image.Height>
<Image.Width>200</Image.Width>
</Image>

It will show the small image in compare to the above.

WPF image control with height and width

The control have all the common properties except some special e.g.
  • SnapsToDevicePixels: whether this control should use device-pixels settings.
  • Source: get or set the image source for the image.
  • Stretch: how an image should be stretched e.g. fill, none, uniform and etc.
  • StretchDirection: specifies the direction of stretch i.e. up, down or both.
It have much more methods and events as like other controls. The above line of code can also be written in the c# language in code behind file:
Image imageControl = new Image();
imageControl.Source = new BitmapImage(new Uri("wall.jpg",UriKind.Relative));
imageControl.Height = 200;
imageControl.Width = 200;

It will show the same image as in above XAML code with width and height specified.

© Copyright 2013 Computer Programming | All Right Reserved