-->

Friday, December 25, 2015

Solve Application not responding problem

In this article, I will show you how to fix computer hanging problems. Generally, we all know about "Not Responding" problem. When processor takes time to execute the process then thats type of problem occurs. By using this article, I will resolve this issue.




Windows Form Design:

Solve Application not responding problem
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication5
{
    public partial class Form1 : Form
    {
        private readonly SynchronizationContext synchronizationContext;
        private DateTime previousTime = DateTime.Now;
        public Form1()
        {
            InitializeComponent();
            synchronizationContext = SynchronizationContext.Current;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (var i = 0; i <= 1000000; i++)
            {
                label1.Text = @"Count : " + i;
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            var count = 0;

            await Task.Run(() =>
            {
                for (var i = 0; i <= 1000000; i++)
                {
                    UpdateUI(i);
                    count = i;
                }
            });
            label1.Text = @"Count : " + count;
            button1.Enabled = true;
            button1.Enabled = false;
        }
        public void UpdateUI(int value)
        {
            var timeNow = DateTime.Now;

            //Here we only refresh our UI each 50 ms
            if ((DateTime.Now - previousTime).Milliseconds <= 50) return;

            //Send the update to our UI thread
            synchronizationContext.Post(new SendOrPostCallback(o =>
            {
                label1.Text = @"Count : " + (int)o;
            }), value);

            previousTime = timeNow;
        }
    }
}

Wednesday, January 8, 2014

How to Create and Use of Iterators, yield: CSharp Programming

Programmer often use some type of iterators that are used to iterate steps in the programming language. An iterator often use yield keyword to return individual element, this is possible only if it have the current location in the cache.

C# Programming uses these iterators to execute some steps continuously like returning a value continuously from a method. Following program is creating an iterator in c# language.

public Form()
{
InitializeComponent();
foreach (int number in SomeNumbers())
{
string str = number.ToString() + " ";
}
}
public static System.Collections.IEnumerable SomeNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}

Yield keyword keeps the current position of the currently executing statement, so that the iteration can be performed.

Here Foreach keyword is used for looping statements in c# programming language, but it is also used as iterators. Each time when the SomeNumbers() method is called in this loop, the yield keyword will return the specified number and will back to the current position.

That is why the resulting string in str variable will be "1 2 3". There may be many ways to creating iterators like:

Using Collection Class: As the well-known class collection is used to automatically called GetEnumerator method which returns IEnumerable type of data. The same process can be easily implemented using this collection class.

Using Generic List: As GetEnumerator method returns an array of specified elements. Generic method is inherited from IEnumerable interface. Using this method iterators can easily be implemented as in above program.

Tuesday, December 24, 2013

How to Delete Multiple Records from DataGridView in Winforms: C#

To remove multiple records from the DataGridView, programmer need to write some line of code, code may be written in a button's click event that is outside of the DataGridView. The article shows about how to select multiple records of DataGridView and the c# code to remove them with a single mouse click.

When a programmer have to remove a single record entry from the DataGridView, then a command button can be added as discussed. Removing a single record can be performed by the index of the record. Through the index programmer can easily get all the unique values about the record which helps to perform the action.


To remove multiple records, follow the steps written below:
  • Drag-n-Drop DataGridView on the form and set its MultiSelect property to True.
  • Create a list of records (Student Class) and bind this DataGridView with that list.
  • Create a button outside of this DataGridView and generate its click event.
  • Write following C# code in the click event of button to remove multiple records:
private void removeButton_Click(object sender, EventArgs e)
{
DataContext dc = new DataContext();
foreach (var item in dataGridView1.Rows)
{
DataGridViewRow dr = item as DataGridViewRow;
if (dr.Selected)
{
string name = dr.Cells["Name"].Value.ToString();
var student = dc.Student.FirstOrDefault(a => a.Name.Equals(name));
if (student != null)
{
dc.Student.Remove(student);
}
}              
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = dc.Student;
}
  • Run the form and select some of the records as in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#

  • Click on the remove button and all these selected records will be deleted. A single record remain safe shown in the image:
How to Delete Multiple Records from DataGridView in Winforms: C#


So all these simple steps are used to delete multiple as well as single record from the DataGridView. Programmer can also use a confirmation message for the surety of the deletion by the user. To do that, just place all the above code in between the below c# code:

if (MessageBox.Show("Are you sure you want to remove all these records?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question).ToString() == "Yes")
{
//above code
}

When the programmer will click on the button then a confirmation message will be shown. After clicking on the "Yes" button, all the selected records will be deleted otherwise none of them.

Monday, December 16, 2013

Computer Programming : Nullable types, Null coalescing operator in c# Programming

In Computer Programming, C# Data types are divided into two broad categories such as Value types and Reference type. In Value types, some inbuilt types such as int, float, double, structs, enum etc. These all are non-nullable types, it means these types don't hold null value. In other hand Reference types such as string, Interface, Class, delegates, arrays etc. can hold null value.
By default value types are non nullable. To make them nullable use, programmer have to use ?
  • int a=0   a is non nullable, so a cannot be set to null, a=null will generate compiler error
  • int ?b=0  b is nullable int, so b=null is legal

Operator Need

If programmer want to assign null value to non-nullable data types then there are some operators explained with an example. 

Lets take an simple example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a;
            int? b = 100;
            a = b ?? 0;
            System.Console.WriteLine(a);
            Console.ReadKey();
        }
    }
}
Computer Programming : Nullable types, Null coalescing operator in c# Programming

Output show that if b hold some value like 100 then Null coalescing operator assign value to variable (a). If b hold null value then Null coalescing operator assign default value, which is zero to variable a. 

Replace the declaration of variable b with the following line:
            int? b = Null;
This will outputs zero (default value).

Friday, December 13, 2013

Computer Programming: Operators in c# console application

Introduction

It is a symbol, which is performed operation on operands, operation can be mathematical or logical. In c#, operators are categories in three basic parts first one is unary operator and second one is binary operator and last one is ternary operator. In unary operator we use single operand like.
++a // here a is a "operand"
In Binary operator we use two operand. Like
a+b;
In ternary operator we use three operand like
a>b?a:b

Assignment Operator (=)

if we create a variable of type integer also we want to initialize it with some value then we should use assignment operator like.

int a=10;

Here, variable a is initialized with value 10. It means you can say the right hand side value is copy to left hand side variable using assignment operator.

Arithmetic Operators ( +,-,*,/,%)

Basically arithmetic operators are used for doing mathematical calculation like addition of two or more numbers , multiplication, division, subtraction, and remainder. lets take a simple example to understand arithmetic operators. If the total collection by five students is five thousand then find the average value?.
int collected_money=5000;
int total_student =5;
int avg=collected_money/total_student;


Ternary operator (?, : )

In ternary operator we have three operands, in which first operand is used for check the condition and other two operands is used for giving results. Let’s take a simple example to understand the ternary operator.

Int firstnumber=10;
Bool result;
Result = firstnumber>10? True: false;

In the preceding example, if condition becomes true or you can say if firstnumber is greater than to 10 then ternary operator gives  ‘true’ in results otherwise gives ‘false’.
 

Comparison Operators (< , > ,<=,>=,!=,==)

using comparison operator you can perform Boolean operation between operands known as comparison operator. Lets take an simple to understand comparison operator
 
 class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            if (a==10)
            {
                Console.WriteLine(string.Format("The value of variable ={0}", a));
  
            }
            Console .ReadKey (false);
        }
    }
 
Computer Programming : Operators in c# console application Here, condition if check equality operation between operands, a and constant value 10. If condition becomes true, output comes "The value of variable=10".


 

  

  Logical operator (&&,|| )

Perform logical operation between Boolean operands known as logical operator. Lets take a simple example
 
  class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = true;
            if (a&&b)
            {
                Console.WriteLine("condition becomes true");
  
            }
            Console .ReadKey (false);
        }
    }
 

Saturday, June 1, 2013

Change textbox value according to Combo Box in c# programming: WinForms

In our previous post we have learnt perform binding Combo Box and Listbox, now it’s time to get access their values and use them to bind another controls in winforms. I am binding a combo box with an employee list and them access data in textbox in c# programming.


For example we have a c# class Employee having following properties:

public class Employee
{
        public int No { get; set; }
        public string Name { get; set; }
}

Create an object of type List of employee (in our Form1.cs file) that will be used to in binding of combo Box

List<Employee> empList = new List<Employee>();

To bind with combo Box this list should have some set of items, so we will add some employees with use of following code in our Form1's constructor:

empList.Add(new Employee() { No = 111, Name = "Venkatesh" });
empList.Add(new Employee() { No = 222, Name = "Muthu Kumaran" });
empList.Add(new Employee() { No = 333, Name = "Murli Prasad" });
empList.Add(new Employee() { No = 444, Name = "Ghosh Babu" });
empList.Add(new Employee() { No = 555, Name = "Jacob Martin" });

Now using following two lines of code we will bind our comboBox with this above list of item

comboBox1.DataSource = empList;
comboBox1.DisplayMember = "No";

When Form1 will run, combo Box will have above list of items and textbox will be empty. To display related value of employee name we have to write these two lines of code with combo Box binding:

Employee selectedEmployee = comboBox1.SelectedItem as Employee;
textBox1.Text = selectedEmployee.Name;

Now our article’s main aim is to binding a textbox with combo Box selected value, so there is an Event of combo Box i.e. comboBox_SelectionChanged event. So I will repeat the most recent two lines of code in this event as written below:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     Employee selectedEmployee = comboBox1.SelectedItem as Employee;
     textBox1.Text = selectedEmployee.Name;
}

Check your windows form application, when you change the selected item of combo Box it will also change the related name of Employee in textbox’s text property.

Download Example

How to Perform Binding with DataGridView in WinForms

The DataGridView control provides a powerful and easiest way to display our data in tabular format with entity framework 5. We can use DataGridView as we want to, like we can use it to simply show our read-only data or we can use it with editable views of our data, in c# programming. Access data from the database and perform binding steps to show them in datagridview.

To do binding on DataGridView with our data is straight-forward and in many cases it is as simple as setting the DataSource property of DataGridView. As DataGridView supports standard binding model, so it will bind to some instances of c# classes like DataSet, DataTable, BindingList and BindingSource etc.

The first way to bind our datagridview to table of database is:

studentDataGridView.DataSource = "DataSet Name";
studentDataGridView.DataMember = "Table Name";


Let’s suppose we have a c# class Student having some properties like following:

public class Student
{
       public int Id { get; set; }
       public string Name { get; set; }
       public string RollNo { get; set; }
       public string Branch { get; set; }
}

Now we will bind datagridview to list of students as:

DataContext dc = new DataContext();
var studentList = dc.Student;
studentDataGridView.DataSource = studentList.ToList();

Here ToList() method is used to convert our DbSet<Student> type of data to List<Student> type of data, because DbSet<> type of data cant be directly bind with any control.
Now if we want to bind only Name and Branch column of Student class then:

DataContext dc = new DataContext();
var studentList = from d in dc.Student
select new
{
d.Name,
d.Branch
};
studentDataGridView.DataSource = studentList.ToList();

We can bind our desired columns to datagridview as we have done in above code. DataGridView doesn’t have any mean where is data come from, so we can use conditions in our queries also.

See Also: DataGridView binding with DataSet

Monday, May 27, 2013

Combo Box or List Box Binding with Database, Entity Framework 5

Most often when we have a list of items and want to select a single item at a time then we can use Combo Box or List Box in winforms application. The basic difference in both is: In List Box one can select an item only from existing list of items whether in Combo Box one can write his/her own new data that can be added to our binding list.

There are some properties that are used to bind a list of items in c# programming i.e

  • Data Source
  • Display Member
  • Value Member
DataSource property will decide the list of data that is to be bind. It may be a Database, Web Service and an object. When this property is set, the item collection cannot be modified at run time.

DisplayMember property indicates the name of an object contained in DataSource property. It denotes what object will be displayed to the user. The default value is empty string.

ValueMember property is used to get the value associated with the control when we are accessing the selected item property.

Let's suppose we have an employee class with properties as shown below c# class:

public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }

Now following code is used to get all records of employee from Database into a var type of variable named employees as given below:

DataContext dc = new DataContext();
var employees = from emp in dc.Employees
                          select emp;

In the above code employees variable have IEnumerable<Employee> type of data and this type of data cannot directly bind to data source property of a control in our programming language. So we have to convert it to a List<Employee>.
To convert this simple type of data a ToList() method is sufficient.

In case of Combo Box

ComboBox1.DataSource = employees.ToList();
ComboBox1.DisplayMember = "Name";
ComboBox1.ValueMember = "Id";

In case of List Box

ListBox1.DataSource = employees.ToList();
ListBox1.DisplayMember = "Name";
ListBox1.ValueMember = "Id";

Here ToList() method is used to convert IEnumerable<Employee> type of data to List<Employee>.
Now when we run our project we will see the list of employees Names in the item collection of Combo Box or ListBox.
© Copyright 2013 Computer Programming | All Right Reserved