Category Archives: Visual C#

How to find sum from obervablecollection list in C#

This example shows how you can simply find aggregate functions like sum, average etc from a Obervablecollection list.

ObservableCollection and Model-View-ViewModel is a ideal for a typical WPF application, these are programmers two of the best tools.

In this example I am using a model class , and want to find sum of inventory qty from batch list.

double qty=_batches.Sum((b) => b.qty));

Here _batches is representing the ObservableCollection of Model batch.

Add records to SQL DB using command builder and dataset in C#

When I talk about C# Dataset quote that it can also be used for insertion of data into the table too. In this post, we are going to learn how to.


  1. Data connection with SQL
  2. Dataset
  3. Command builder object

In our example, we had MiniPurchaseInfo table and dataset associated with it.  First thing first, the dataset

SqlDataAdapter MiniPurchaseInfo = new SqlDataAdapter("select * from minipurchaseinfo", con);
 MiniPurchaseInfoDataSet = new DataSet();
 MiniPurchaseInfo.Fill(MiniPurchaseInfoDataSet, "minipurchaseinfo");

We simply make the query, filling the information to the dataset and so on. The next step is to create a row with the DataRow object and add the data row to our dataSet object.

DataRow dro;

dro = MiniPurchaseInfoDataSet.Tables[0].NewRow();
 dro["entryno"] = entryNo;
 dro["supinvoice"] = txt_invoice.Text.ToString();
 dro["supid"] = SUPID;
 dro["netamount"] = net;

add the row to the dataset.


The final step is to set up the command build which has the capability of insertion and deletion operations with DB adapter and dataset.

System.Data.SqlClient.SqlCommandBuildercmdbuilder = new System.Data.SqlClient.SqlCommandBuilder(MiniPurchaseInfo);

Set insert command of the adapter from the command builder object

MiniPurchaseInfo.InsertCommand = cmdbuilder.GetInsertCommand();

Call the update command of the adapter which will update the new row stored in the dataset into the database table.

int r = MiniPurchaseInfo.Update(MiniPurchaseInfoDataSet.Tables[0]);

The update will return a none zero value when the insertion performed.

ListCollectionView for sorting,filtering data collection

When we wanted to perform filtering, sorting of data over a binded data collection, collection view might be helpful. If the source collection implements INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are reflected to the views.

ListcollectionView Represents the collection view for collections that implement IList as Mictosoft Doc says.

Create a collection view

In order to use ListCollectionView you have to use ObjectModel

using System.Collections.ObjectModel;

Then you can use any list to create ListCollectionView, in this example I used my observable collection of SalesOrder.

ListCollectionView sorderview = null;
collectionview = new ListCollectionView(salesOrderCollection);

Model View Class

class SalesOrderView
    {   public DateTime Date { get; set; }
        public string Customer{ get; set; }        
        public string Amount{ get; set; }

Create a Custom filter

Let’s play with filter, first up all we need to create some custom filter for searching SalesOrders received from customers on a specific date

collectionview.Filter = (e1) =>
                    SaleOrderView sorder = e1 as SaleOrderView ;
                    if (((Convert.ToDateTime(sorder.Date) >= dtp_from.SelectedDate && 
Convert.ToDateTime(sorder.Date) <= dtp_to.SelectedDate)) )
                        return true;
                    return false;

That is it, now you can simply bind the collection view with DataGrid or Listcontrol. For me it is a Grid

 mydatagrid.ItemsSource = collectionview;

C#Tips/Tricks – XAML Formating

Do you know , within XAML element of you C# WPF application , the binded data can be formated using string format. For a date field you can use the following style

<TextBlock x:Name="tbl_fy" Text="{Binding [0].f_date1,
 StringFormat={}{0:MMM/dd/yyyy}}" Foreground="Beige"
 FontSize="14" Width="119"/>   

C#Tips/Tricks – Linq and Functions

Do you know Linq in c# has special capabilities to handle data smoothly. As we learned you can operate on user defined types and list using Linq.

Even you can use your own functions from within the Linq

C# Linq

The following example illustrate how to use functions within Linq

 var salesSummary = (from s in salesTable.AsEnumerable()
                           join c in Customer.AsEnumerable() on s.Field<int>("cid").ToString() equals
                           select new
                               sv= new SalesView()
                                   Date = s.Field<DateTime>("date"),                                   
                                   invice = s.Field<int>("vno"),                                   
                                   Customer = c.Field<string>("name"),
                                   Amount = string.Format("{0:0.00}", s.Field<decimal>("amount")),                 
 InvBalance = string.Format("{0:0.00}", GetActBalance(s.Field<DateTime>("date"), s.Field<int>("cid"), s.Field<string>("vno"))),                  

In the above example I used a function GetActBalance to display, the invoice balance at the point of sale , assume that they may paid some amount at the time of sale.

C#Tips/Tricks – Linq to array

You can easily convert a data table rows into object array using Linq query in C#.Net

var names_array = (from cols in tblcols.AsEnumerable() select cols.Field<string>("student_name")).ToArray();

Array can be used to supply items to list box and combo box controls as follows

 listbox1.Items.AddRange(names_array );

DataGridView meets Linq

DataGridView is a tool for displaying, modifying, entering values in Visual Studio.Net. Usually we are using loops or readers to traverse through rows or columns.

Linq query make it possible to do these take with few lines, instead of complicated loops.

We have a data entry GridView which accepts purchase details such as name,qty,price etc. Lets get the sum of quantity supplied in the grid using Linq query

We do the following

  1. Create List of values
  2. Call the Sum() for total function for the column we specified

The Linq Querry

var qt = from DataGridViewRow row in dataGridView1.Rows where row.Cells[COL_QTY.Index].FormattedValue.ToString().Trim().Length!=0 && row.Cells[COL_QTY.Index].FormattedValue != null select ( row.Cells[COL_QTY.Index].FormattedValue.ToString().Trim());

We have to make sure the cell is not null or it has any values at all, we place where section, otherwise the System will fire you for an unhandled exception, lol.

Summing up values

txt_tqty.Text = qt.Sum(c => Convert.ToDouble(c)).ToString();

That’s all

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 Split strings using separator symbols in C#

We had some interesting string as follows which need to split and take the desired portion. C#.Net provides special string function called Split, which helps you broke complex strings into fragments.

Here are our Stings look like

121 | Whole Sale Rate

131 | Retail Rate

We begin with initialization of string and then build separator array, then call the split method. I guess you are familiar with the string array if you don’t just look at the 3rd line.

string  st=”121 | Whole Sale Rate”;

Here  “|” is the separator

string[] separator= { “|” };

string []selRateStr = null;

Let’s split the string with Split, which is the function available with string object also with ToString() too.

selRateStr =st.Split(separator,StringSplitOptions.None);

the first element in the selRateStr will be 121, which can be accessed as selRateStr [0];

Here is the authentic link from MSDN which may help you to learn Split function in detail.