I actually do this a lot, here’s how:
foreach (DataGridViewRow gridrow in DataGridView.Rows)
{
DataRow datarow = (gridrow.DataBoundItem as DataRowView).Row;
// do something with the datarow
}
I was using NUnit today, and wrote a very simple quick start sample for all of those interested in using NUnit ASAP.
NUnit according to nunit.org is a “unit-testing framework for all .Net languages”. In simple words, you can test your code, and make sure it’s doing what it’s supposed to do. My sample is going to make sure a class called “Addition” adds correctly.
If you don’t have NUnit in your machine visit nunit.org.
I created in Visual Studio two different C# projects with different class libraries (.DLL) in each project. The first project is a simple Addition class:
Addition.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace AdditionDLL
{
public class Addition
{
public int Add(int number1, int number2)
{
return number1 + number2;
}
}
}
This only takes two numbers and adds them. Don’t forget to build your project, so you .DLL gets created.
Our first DLL needs to be in the reference of our second project and also the NUnit.Framework.dll which in my computer is in “D:\Program Files\NUnit 2.4\bin\nunit.framework.dll”
Here’s how the references of my second project looks:

The second class library contains the code that is going to make sure that my Add method in the Addition Class , adds correctly. Here’s the code for my other class
Test.cs
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using AdditionDLL;
namespace NUnitTest
{
[TestFixture()]
public class Test
{
[Test]
public void Scenario()
{
Addition add = new Addition();
int result = add.Add(1,2);
int expectedResult = 4;
Assert.IsTrue(result == expectedResult, "The result needs to be 3");
}
}
}
There are interesting things about this class.
- Before the class starts you will notice this statement: [TestFixture()]. This basically means that this class contains test cases.
- Before the scenario method you will notice this statement: [Test]. This basically means that this method is going to be tested.
- Inside the scenario method, there’s the following line: Assert.IsTrue(result == expectedResult, "The result needs to be 3");. This verifies if result is equal to the expected result. If the assertion fails it displays a message which in this case is that “the result needs to be 3″.
Now I’m going to open NUnit,which should be somewhere in your Start-> All Programs -> NUnit
When you open NUnit create a new project, name it and save it.
After you create a project, under Files click “Open Project” and in here look for NUnitTest.dll, which should be in the Debug folder of your NUnitTest Project (assuming you are following this example ).
After this step you should see something like this:
If you press “Run” you should see something like this:
As you can see my test failed. This is because 1+ 2 = 3, and it’s expecting 4 as the result of the sum.
If you change line 17 in Test.cs to:
int expectedResult = 3;
save the file in visual studio, rebuild solution, open project in NUnit, and choose NUnitTest.dll, and run it again, you should see something like this
Hope this can get you started!
I have been using Orcas Express Edition to start playing around with the WPF (Windows Presentation Foundation ) windows.
I was trying to build a menu which has several report options, and when the user clicks on a menu you can see the report in the datagrid. In this post I’m only going to write about building the menu.
Here’s an example of a menu in WPF:
<Menu Width=”100″ Margin=”0, 0, 0, 0″ HorizontalAlignment=”left” Background=”White”>
<MenuItem Header=”_File”>
<MenuItem Header=”_New” Click=”DisplayNew”/>
<MenuItem Header=”_Open” />
</MenuItem></Menu>
When you create a WPF Window, it creates two files, e.g: Window.xaml,Window.xaml.cs.The XML this example uses is called XAML ( which is inside my Window.xaml ), which is used in the .NET Framework 3.0 technologies, specially in WPF. The interesting thing about this WPF concept is that if you are interested for a control to have certain event you need to specify it in the XAML. As you can see when the user clicks “New” in my menu, I’m going to call a method called “DisplayNew” which is inside my Window.xaml.cs.
The Window.xaml.cs will look like this:
private void DisplayNew(object sender, System.Windows.RoutedEventArgs e)
{
// In here you can decide what to do when the menu item is clicked
}
In the Window.xaml.cs you actually need to type this method manually. It will not be created for you by Orcas. So this is how the example should look:

I was building a Windows Presentation Foundation browser application, and somewhere in my code I was trying to open a SqlConnection, and the error appeared.
“Request for the permission of type ‘System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.”
I had this annoying bug, which at the end it wasn’t that bad to solve.
The solution:
If you do a right click in the properties of your solution, and you go to security, click on “This is a full trust application”. This should solve this problem.
I would also like to thank Animesh for his input in this topic. He had another solution to it, and according to him “There was a change needed in web.config. Increased the trust level to full for security policies and it worked”.
If you have another way to solve this problem, please comment it, and let me know.
Lately, I have been putting my programming practices to the test with FxCop. FxCop makes sure your code conforms the best .NET coding practices.
I will write in a separate post how to use FxCop, but for the moment i will write about some of the improvements FxCop suggested for my code.
Warning, Certainty 95, for UseLiteralsWhereAppropriate
{
Resolution : “Field ‘MOST_ACTIVE’ is declared as ’static readonly’
but is initialized with a constant value ‘Most Active’.
Mark this field as ‘const’ instead.â€
}
The line that was causing this warning:
private static readonly string MOST_ACTIVE = “Most Activeâ€;
Solution:
private const string MOST_ACTIVE = “Most Activeâ€;
Warning, Certainty 95, for TestForEmptyStringsUsingStringLength
{
Resolution : “Replace the call to String.op_Inequality(String.Empty)
in ‘MyDefaultPage.Populate(String, String):Void’ with
a call to String.IsNullOrEmpty.â€
}
The line that was causing this warning:
if (panel != String.Empty)
Solution:
if (!String.IsNullOrEmpty(panel))
Warning, Certainty 90, for DoNotInitializeUnnecessarily
{
Resolution : “MyDefaultPage.MyDefaultPage() initializes field
behavior of type DeltaOptions.Windows.Forms.Behaviour.IReportFormBehavior
to null. Remove this initialization as it will be done
automatically by the runtime.â€
}
The line that was causing this warning:
private IReportFormBehavior behavior = null;
Solution:
private IReportFormBehavior behavior;
Warning, Certainty 95, for RemoveUnusedLocals
{
Resolution : “MyDefaultPage.Populate():Void declares a local,
‘mypageOptions’, of type System.String, which is never
used or is only assigned to. Use this local or remove
it.â€
}
The line that was causing this warning:
Some variable that wasn’t being used in a method
Solution:
Delete or comment the variable not used.
These are some of the multiple warnings that FxCop can point about your code. As you noticed, running your code against this tool will improve your source code greatly.
The purpose of this post is to show you how to display a WPF Window with a datagrid that contains data from a SQL Server Database.
The version of Orcas I’m using doesn’t have a Datagrid between their tools. Consequently, I’m using Xceed’s Datagrid which according to them is “the world’s first data grid control for Microsoft’s Windows Presentation Foundation”. Very interesting!
I installed this datagrid, and at first I thought it would appear under my tools in Orcas. I thought this because i’m used to drag and drop my controls to the form. However, I later found out that to be able to display the grid in my WPF window, I needed to add the grid in the XAML file. This is an example:
Window1.xaml
<Window x:Class=”WPFTrading.Window1″
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:xcdg=”http://schemas.xceed.com/wpf/xaml/datagrid”
Title=”Window1″ Height=”250″ Width=”800″ WindowStyle=”ThreeDBorderWindow”>
<Grid Name=”dataGrid1″>
<xcdg:DataGridControl x:Name=”ordersGrid”
ItemsSource=”{Binding Source={x:Static Application.Current},Path=Orders}”>
</xcdg:DataGridControl>
</Grid>
</Window>
Now I’m going to explain the parts in bold:
xmlns:xcdg=”http://schemas.xceed.com/wpf/xaml/datagrid”
This is xceed’s namespace. If you don’t have this line you will get a compiler error saying “”xcdg’ is an undeclared namespace.”
<xcdg:DataGridControl x:Name=”ordersGrid”
ItemsSource=”{Binding Source={x:Static Application.Current},Path=Orders}”>
</xcdg:DataGridControl>
This is xceed’s Datagrid. The name of my Datagrid is ordersGrid. In ItemsSource I’m basically binding the grid to the Orders table.
This is all the XAML you need for the Datagrid to appear in your window. However, at this point your datagrid has no data at all.
When you create a WPF Window project an App.xaml and App.xaml.cs files are created. This files are important because in the App.xaml you can do several things. One of them is to set in what window the application is going to start. Here’s an example:
App.xaml
<Application x:Class=”WPFTrading.App”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:xcdg=”http://schemas.xceed.com/wpf/xaml/datagrid”
StartupUri=”Window1.xaml”>
</Application>
Now I’m going to explain the parts in bold:
StartupUri=”Window1.xaml”
As you can notice when my project starts, it loads Window1.xaml
At this point, I’m going to write about how to put some data in the datagrid. I did this in my App.xaml.cs. Here’s the pseudocode of it:
App.xaml.cs
private DataTable mOrders;
public DataTable Orders
{
get { return mOrders; }
}
protected override void OnStartup(StartupEventArgs e)
{
Xceed.Wpf.DataGrid.Licenser.LicenseKey = "Your key goes here";
// create a connection string
string connectionString = "Your connection string goes here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
// open a connection
connection.Open();
// create a sqlcommand
SqlCommand command = new SqlCommand();
command.CommandText = "Your SELECT statement goes here";
// create a dataset
DataSet ds = new DataSet();
// create a sqldataAdapter
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, connection);
// fill the adapter
adapter.Fill(ds);
// fill the orders table
mOrders = ds.Tables[0];
// close connection
connection.Close();
// raise the Startup event.
base.OnStartup(e);
}
}
Some observations:
- You need a key for your datagrid. If not you will get a LicenseException.
- Make sure you paste the code in notepad and not microsoft word, since you might have problems with the quotes. Make sure the quotes are correct.
- I didn’t post my connection string because it varies.
At the end I ended up with a datagrid like this:

Pretty cool!!!
Today I’ve been wondering how to set a DataGridViewComboBoxColumn to a default value. The reason I wanted do this, is because i want the combo box to have a default value when the datagridview is loaded in the screen.
The line to accomplish this is the following:
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.NullValue = "Buy";
I was trying to have a datagridview with a column that has a checkbox.
This is how I did it:
DataGridViewCheckBoxColumn ckbLotsOf = new DataGridViewCheckBoxColumn();
ckbLotsOf.Name = "chkLotsOf";
ckbLotsOf.HeaderText = "Lots of";
ckbLotsOf.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGrid.Columns.Add(ckbLotsOf);
DataGridViewCheckBoxColumn creates the column with a checkbox. Your column needs a name, the text of the header of the column, autosize the column so it doesn’t take too much space, and then just add the column to the datagrid.