break
Aug 25

If you want a basic quick start in LINQ this is going to help you.

LINQ according to the research I did in MSDN is a “set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations.” In MSDN they define LINQ in simple terms, and state that “LINQ is a series of language extensions that supports data querying in a type-safe way”. The last interesting fact I found in MSDN about LINQ is that “the data to be queried can take the form of XML, databases, objects, and so on”.

There’s a lot of theory about LINQ in MSDN and in the internet, but my purpose is to give you a quick start in how to start coding LINQ applications.

The first step is to download the “Language Interated Query, May 2006 Community Technology Preview”. The link to this preview is here.

The importance of installing this extension is that if you go to Visual Studio 05, and press File->New->Project , you will see in your Visual C# tree a node that says “LINQ Preview” which will give you the option to create a LINQ Console Application, LINQ Windows Application, LINQ Library, and LINQ WinFX Application.

For this introduction I’m going to choose a LINQ Windows Application. When a LINQ Windows Application is created you will be able to see DLL’s needed for LINQ applications such as: System.Data.DLinq, System.Data.Extensions, System.Query, System.Xml.XLinq.

Now that you have your LINQ Windows Application created, the task will be the following:
Display an array of strings ordered alphabetically in a listbox.

This is how you can do this:

private void Form1_Load(object sender, EventArgs e)
{
string[] names = { "Daniel", "Lesseps", "Isaacs", "Diaz" };
var namesToDisplay = from name in names
orderby name
select name;
foreach(var name in namesToDisplay)
listBox1.Items.Add(name);
}

When our form loads the first line declares an array of strings that contains 4 words.

The next line is a sample LINQ query, and I will explain this line as I understand it (which means that if you have any input on my explanation it will be appreciated) . As you can see LINQ queries start with “var” which indicates it’s a local variable. The LINQ query contains clauses like: FROM, WHERE, SELECT,ORDERBY, GROUP BY, and others. This example starts with “from name in names”. The part “in names” is very important since it’s specifying the list that is going to be queried. After this I’m ordering the names alphabetically using “orderby name”. The last line of the query is the “select name(you can think of name as the name of my column)”. SQL queries start with the SELECT clause; however, LINQ queries end with the SELECT clause.

var namesToDisplay = from name in names
orderby name
select name;

After this we iterate the results of the query using a foreach, and each statement returns a name.

As you can see, SQL queries can now be integrated in C#.
Very interesting! This is a basic example,I will write more complex examples later on.

Aug 18

If you run the code below you will notice the following behavior:

For some reason when I press a button and the button puts an error text in my cell (because of an error validation) when I go back to the cell, it selects all the text in the datagridviewcell and if you press a number you are going to be able to watch two behaviors:

1- The Datagridviewcell adds itself:
This was happening in my real world application.
For example, if I have a number like 1111.000 (let’s say this sends a validation error), if you go back to the cell and press “1″ you will see something like
1111.001
If you press “5″ you will see something like
1111.002
If you keep pressing numbers you will see that you will be adding your current number.

2- The Datagridviewcell will only let you put one number at a time.
This is what happens in the code below. If you press 1111.000 and you go back to the cell and press “1″ you will see something like
1.000

If you press “2″ instead of being 12.000 or 1.002 you will see
2.000

It will only let you put one number at a time.

Here’s the code for this scenario


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace DataGridViewBugBlog
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
InitializeGridColumns();
FormatDataGridColumn(dataGridView1, "Price", typeof(double), null);
}
private void InitializeGridColumns()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.AddRange(new System.Data.DataTable[] {dt});
// Adding columns to the DataTable
dt.Columns.Add("Quantity", typeof(double));
dt.Columns.Add("Price", typeof(double));
dataGridView1.DataSource = ds.Tables[0].DefaultView;
// Setting the width of both columns
foreach (DataGridViewColumn col in dataGridView1.Columns)
col.Width = 95;
}
private void button1_Click(object sender, EventArgs e)
{
showConfirmation();
}
///

/// If the price or quantity doesn't have a correct
/// format it will send a messagebox.
///

private void showConfirmation()
{
bool error = false;
foreach (DataGridViewRow mRow in this.dataGridView1.Rows)
if (!ValidateData(mRow))
error = true;
if (error)
MessageBox.Show("Invalid quantity or price, please check and reenter", "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
///

/// The valid format for the price
/// is 000,0000
///

private bool ValidateData(DataGridViewRow mRow)
{
bool ok = true;
string txtPrice = "Price";
//quantity format
if (!Regex.IsMatch(mRow.Cells[txtPrice].FormattedValue.
ToString(), @"(?!^0*$)(?!^0*\.0*$)^\d{1,3}(\.\d{1,4})?$"))
mRow.Cells[txtPrice].ErrorText = "Please enter a valid numeric format. Ex (000,0000) ";
ok = false;
return ok;
}
///

/// This event handler manually raises the CellValueChanged event
/// by calling the CommitEdit method. The event CellValueChanged
/// was used to handle DataGridViewCheckBoxCell logic.
///

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty && dataGridView1.CurrentCell.ColumnIndex >= dataGridView1.Columns["Price"].Index)
dataGridView1.
CommitEdit(DataGridViewDataErrorContexts.Commit);
}
internal static void FormatDataGridColumn(DataGridView dataGrid, string col, Type type,
string format)
{
DataGridViewColumn column = dataGrid.Columns[col];
if (type == typeof(Double))
column.DefaultCellStyle.Format = format == null ? "##0.0000" : format;
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
}
}
}

This only an excerpt of my code. The interesting part about this, is that what causes this error is the CurrentCellDirtyStateChanged event. I had this event because inside of it i had a CommitEdit method that raises the CellValueChanged event in which I was changing the values of some DataGridViewCheckBoxCell.

The solution:
Make sure in the CurrentCellDirtyStateChanged the CommitEdit is only made when you are in a DataGridViewCheckBoxCell. For the code above just comment the CommitEdit method and it will work like it should.

Aug 1

A friend of mine asked me How to add an item to a ListView using a WPF ListViewItem.

First of all, you can add items to a <ListView> either in the XAML, or in the .cs file of your project using the following line:
listView1.Items.Add("Daniel");

But if for some reason you want to use a ListViewItem you can do something like this:
Window1.xaml

<Window x:Class=”WPFListView.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Title=”Window1″ Height=”300″ Width=”300″>
<Grid>
<ListView Margin=”65,85,107,86″ Name=”listView1″ />
</Grid>
</Window>

Window1.xaml.cs

public Window1()
{
InitializeComponent();
ListViewItem item;
List < string > items = new List< string >();
items.Add(”Hello”);
items.Add(”Daniel”);
foreach (string names in items)
{
item = new ListViewItem();
item.Content = names;
listView1.Items.Add(item);
}
}

The important part of this code, which is what my friend couldn’t find is that to add a text to a ListViewItem you use the Content property.
listView