Category Archives: DatagridView

WPF: Observable collections for dynamic itemsource


ObservableColeection is ObjectModel collection which can be used to store and l list of objects in .Net. One of the notable feature of this collection is that unlike other collection it can be automatically update itemsources.

Observablecollection implements IObservable Interface

C# ObjectModel collection

Where to use Observable

Observable can be best fit where keep need to observe changing objects. The best example was a registration of student and throught the application you have to access the names, when ever a new registration occurs names should be available without any refresh in all other modules like, on studentmanagement,on fee collection,on attendance etc.

Observable collection aware change in items only when you do add new item, or delete / modify items in the collection.

Followiing example store and modify student scores and dynamically add to a datagrid.

The XAML

<Window x:Class="WpfApp2.MainWindow"
        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"
        xmlns:local="clr-namespace:WpfApp2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="192*"/>
            <RowDefinition Height="227*"/>
        </Grid.RowDefinitions>
        <Button Click="Button_Click" Content="Add" HorizontalAlignment="Left" Height="64" Margin="26,28,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="Clear" Click="Button_Click_1" HorizontalAlignment="Left" Height="72" Margin="26,110,0,0" VerticalAlignment="Top" Width="258"/>
        <Button Content="New Set" HorizontalAlignment="Left" Height="81" Margin="26,0,0,0" Grid.Row="1" VerticalAlignment="Top" Width="258" Click="Button_Click_3"/>
        <DataGrid ItemsSource="{Binding}" x:Name="resultgrid" HorizontalAlignment="Left" Height="245" Margin="344,28,0,0" Grid.RowSpan="2" VerticalAlignment="Top" Width="418"/>
    </Grid>
</Window>

The above code simply bind the grid with itemsource. Have a look at the c# source code.

ObserVableCollection : example

ViewClass

 class Result
    {
        public string sname { get; set; }
        public string grade { get; set; }
        public decimal mark { get; set; }
    }

We are creating a set of objects and create collection of objects and add and modify the collection.

Code behind the collection data

 public partial class MainWindow : Window
    {
        ObservableCollection<Result> studentset = new ObservableCollection<Result>();
        public MainWindow()
        {
            InitializeComponent();
            resultgrid.ItemsSource = studentset;            
            }
       private void Button_Click(object sender, RoutedEventArgs e)
        {

            Result mark;
            mark = new Result() { sname = "Abraham", grade = "A+", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Muhammed", grade = "B", mark = 95 };
            studentset.Add(mark);
            mark = new Result() { sname = "Nikhil", grade = "A", mark = 95 };
            studentset.Add(mark);            
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            studentset.Clear();
        }
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
          Result  mark = new Result() { sname = "John", grade = "A", mark = 95 };
            studentset.Add(mark);
        }
    }

Each time an element to the collection were added , the itemsource is being updated and refreshed.

In my experience Observable collection is best suited for report objects, when ever a new item is added to the report collection your report is being updated, it is like you have a live reporting system.

Tip : You can create Method for adding only new items to the collection instead of removing all of them using Remove method of collection class.

Insert rows to DatagridView in C#.Net/.Net


DataGridView is an easiest option for reports as well as other data operations in C#.Net. In this post I will show how to use methods to add rows to a datagrid from controls like textbox.


We can add new rows to a datagridview in three different ways

  • Using a DataTable
  • Using Add Row method
  • Using Set Value method
With a Data Table

Create a data Table and Row and add it to the Grid using Add method of Rows.

         DataTable dt = new DataTable();
         DataRow dr;
         dataGridView1.DataSource = dt;
         dr = dt.NewRow();
         dt.Columns.Add("Column1");
         dt.Columns.Add("Column2");
         dr["column1"] = "Value1";
         dr["column2"] = "Value2";
         dt.Rows.Add(dr);
With param arguments

The Add method of row can be used to insert rows with array of objects as follows

dataGridView2.Rows.Add("Value1", "Values2");

With Set Value

Same as the above we can also use the SetValue method too

        int rid;
        try
        {
            rid = dataGridView2.Rows.Count;
            dataGridView2.Rows[rid].SetValues("value1", "Value2");
        }
        catch (ArgumentOutOfRangeException exc)
        {
            rid = dataGridView2.Rows.Add();
            dataGridView2.Rows[rid].SetValues("value1", "Value2");
        }

How to add a ComboBox to DatagridView programmatically in C#.Net


DatagridView in C# 2015 is an important tool to show database values. This control has different usage such as regular Grid. Here we explore the different approaches to the datagrid programing which will explaining how to add advanced combo, auto suggestion box etc to DataGridView control.

Easy steps we require

Start a new Windows Form project in your Visual Studio and Drop a DatagridView control to your project, our project require a DataGridViewComboBoxColumn object. Here we goes
  1. Initialize column header with appropriate text
  2. Create a DataGridViewComboBoxColumn object and fill with appropriate values, name and a header text.
  3. Add the DataGridViewComboBoxColumn object to the DatagridView

That’s the plan, just the drop the following code to the form’s load event method.

The C# code

            dataGridView1.ColumnCount = 1;
            dataGridView1.Columns[0].Name = “Slno”;
            DataGridViewComboBoxColumn dc = new DataGridViewComboBoxColumn();
            dc.HeaderText = “Order Items”;
            dc.Name = “Items”;
            dc.Items.Add(“Mango”);
            dc.Items.Add(“Carrot”);
            dc.Items.Add(“Sugar cane”);
            dc.Items.Add(“Potatto”);
            dc.Items.Add(“Grapes”);
            dc.Items.Add(“Chillie”);
            dc.MaxDropDownItems = 1;
            dataGridView1.Columns.Add(dc);
            dataGridView1.Columns.Add(“Qty”, “Qty”);

Lets run, and that’s all you need to know. Next time we will meet with Autocomplete Box poem.