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.


<Window x:Class="WpfApp2.MainWindow"
        Title="MainWindow" Height="450" Width="800">
            <RowDefinition Height="192*"/>
            <RowDefinition Height="227*"/>
        <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"/>

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

ObserVableCollection : example


 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()
            resultgrid.ItemsSource = studentset;            
       private void Button_Click(object sender, RoutedEventArgs e)

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

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();
         dr["column1"] = "Value1";
         dr["column2"] = "Value2";
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;
            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(“Sugar cane”);
            dc.MaxDropDownItems = 1;
            dataGridView1.Columns.Add(“Qty”, “Qty”);

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