-->

Friday, April 15, 2016

Windows Forms Methods

Windows Forms methods enable you to perform various tasks, such as opening, activating and closing the form.

The commonly used methods are explained in the following:
1. Show ( ) 
Description : Is used to display a form.
Example: Form2 frmobj = new Form2();
frmobj.Show();

Explanation : This code creates a new instance of the Form2 form by using the new keyword. The Show() method display the instance of Form2 form.

2. Hide( )
Description: Is used to hide a form.
Example: Form1 frmobj = new Form1();
frmobj.Hide();
//you can use
this.Hide( ); // for current Form1

Explanation: This code creates a new instance of the Form1 form by using the new keyword. The Hide() method hides the instance of Form1 form.

3. Activate ( )
Description: Is used to activate a form and set the focus on it. When you use this method. It brings the form to the front(if it is the current application) or flashes the form caption(if it is not the current application) on the task bar.
Example: Form1 frmobj = new Form1();
frmobj.Activate();
Explanation : This code sets focus on a form named Form1.

4. Close ( )
Description: Is used to close a form.
Example: Form1 frmobj = new Form1();
frmobj.Close();
Explanation: This code closes the form named Form1.

5. SetDesktopLocation()
Description: Is used to set the desktop location of a form at runtime. This method takes the X and Y coordinates of the desktop as its parameters.
Example: Form1 frmobj = new Form1();
frmobj.SetDesktopLocation(200,200);
Explanation : This code displays the form named Form1 at the specified location.

Thursday, April 7, 2016

Types of Dialog Boxes in Windows Form C#

Windows provides the following type of dialog boxes:
1. Modal
2. System Modal
3. Modeless

Modal Dialog Box : A modal dialog box does not allow you to switch focus to another area of the application, which has invokes the dialog box. However, you can switch to other windows application while the modal dialog box is being displayed on the screen.
For example, the Save as dialog box of Microsoft word is a modal dialog box. If you are trying to save a word file by using the Save As dialog box, you cannot make any changes in the word document until it is saved. The following figure shows the save as dialog box.


Modal Dialog Box


System Modal Dialog Box
The System modal dialog box takes control of the entire Windows environment. For example, the Windows Log On dialog box is a system modal dialog box.
The following figure displays the Log On to Windows dialog box.
Sometimes, error messages are displayed by using a system modal dialog box. When such messages appear on the screen, the user is not allowed to switch to, or interact with, any other Windows application until the system modal dialog box is closed.

System Modal Dialog Box


Modeless Dialog Box

Types of Dialog Boxes in Windows Form C#

The modeless dialog box stays on the screen and is available for use at any time. For example, the Find and Replace dialog box of Microsoft Word is a modeless dialog box. This modeless dialog box allows you to switch to another area of the application, which has invoked the dialog box, or to another windows application.

Sunday, January 10, 2016

Change System date Format using c#

If you want to change Your system date format using c# then you must to use RegistryKey class. This class is available in Microsoft.Win32 namespace. By using this class you can change the short and long date format, Before any changes the Date format look like.

Change System date Format using c#

Now, after the code you can change the Date format:

using Microsoft.Win32;

private void button1_Click(object sender, EventArgs e)
        {
            RegistryKey regkey = Registry.CurrentUser.OpenSubKey(@"Control Panel\International", true);
            regkey.SetValue("sShortDate", "10/12/87");
            regkey.SetValue("sLongDate", "10/12/87");
        }

Customized Date Format

Friday, January 8, 2016

Export DataGridView to Excel using OpenXML and ClosedXML

In this article, I will explain you, How to export data of DataGridView to Excel file. In this article, I will use OpenXML and ClosedXml libraries for export data. We can also export data of DataGridView using Foreach loop by fetching each row of it. To do this task, first of all Download two assemblies i.e :

  1. Open XML SDK 2.0 For Microsoft Office 
  2. Closed XML

Now, Add windows form into your project. Add a DataGridView and single button on it.

using System;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Reflection;
using ClosedXML.Excel;

namespace Export_DataTable_Excel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.BindData();
        }

        private void BindData()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("StudentId", typeof(int)),
            new DataColumn("StudentName", typeof(string)),
            new DataColumn("StudentCity",typeof(string)) });
            dt.Rows.Add(1, "Jacob lefore", "US");
            dt.Rows.Add(2, "Ammey smith", "UK");
            dt.Rows.Add(3, "Bill Smith", "Fr");
            dt.Rows.Add(4, "Robert", "Ru");
            this.dataGridView1.DataSource = dt;
        }

        private void ExportExcel_Click(object sender, EventArgs e)
        {
     
            DataTable dt = new DataTable();

 
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                dt.Columns.Add(column.HeaderText, column.ValueType);
            }

   
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                dt.Rows.Add();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
                }
            }

            //Exporting to Excel
            string folderPath = "C:\\my\\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (XLWorkbook xlfile = new XLWorkbook())
            {
               xlfile.Worksheets.Add(dt, "students");
               xlfile.SaveAs(folderPath + "data.xlsx");
            }
        }
    }
}

Code Generates the following output

Export DataGridView to Excel using OpenXML and ClosedXML

Sunday, November 16, 2014

How to add controls dynamically in windows form c#

Visual studio provide the best features to design the form. By the designer window, you can add the controls from the toolBox. After added the items, you can set the properties by the property window. Same this things, you can do this by the code window. Follow some steps to add controls dynamically.


  Step-1 : Open Code window that is form1.cs file, create a object for controls like

TextBox t1 = new TextBox();

Step-2 : Associate properties of the TextBox class with the current object like

 t1.Name = "Text1";
    t1.Width = 300;
            t1.Text = " Dynamically added Control";
            t1.Location = new Point(10, 10);

Here Point is a class, in which you have to define the coordinates of x-axis and y-axis, where you want to add the TextBox.

Step-3 : Add this instance in the form by following line of code.

 this.Controls.Add(t1);

 Now code Generate the following output:
How to add controls dynamically in windows form c#

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.

Friday, December 6, 2013

Moving Records from a DataGridView to Another in C#: WinForms

Drag-n-Drop operation is an important action in the winforms application like our file explorer. This article will let you perform moving items from one datagridview to another, code is in c#. Follow the article and you will easily be able to do this task.

There are series of events that need to be handled to complete this task, discussed in moving items from one CheckedListBox to another. To perform this in datagridview we will use the pre-defined class Student with its properties like name, age and address.
  • Add two DataGridView control to the form (defaultDGV & newDGV) and place them in simple form as shown.

    Moving Records from a DataGridView to Another in C#: WinForms

  • Create two list of type Student class named stuList and newList.
    List<Student> stuList = new List<Student>();
    List<Student> newList = new List<Student>();
  • In the constructor add some records in the first list and bind that to first datagridview.
    public Form1()
    {
    InitializeComponent();
    stuList.Add(new Student() { Name = "Jacob", Age = 29, City = "London" });
    stuList.Add(new Student() { Name = "Zulia", Age = 31, City = "London" });
    stuList.Add(new Student() { Name = "Brandon", Age = 35, City = "London" });
    defaultDGV.DataSource = stuList;
    }
  • Generate MouseDown event of the defaultDGV datagridview and write following code:
    if (defaultDGV.SelectedRows.Count == 1)
    {
    if (e.Button == MouseButtons.Left)
    {
    DataGridView.HitTestInfo info = defaultDGV.HitTest(e.X, e.Y);
    if (info.RowIndex >= 0)
    {
    string name = defaultDGV.Rows[info.RowIndex].Cells["Name"].Value.ToString();
    defaultDGV.DoDragDrop(name, DragDropEffects.Move);
    }
    }
    }
In above code, we have to write code only when any of the row is selected and left mouse button is pressed. HitTestInfo class is used to get information of the specific row at given coordinates. After that get your desired cell value if the row index is greater than zero. DoDragDrop() method will set the value to be dragged.

  • Generate DragEnter and DragDrop events of another datagridview i.e. newDGV and make them same as written with following c# code.
    private void newDGV_DragEnter(object sender, DragEventArgs e)
    {
    e.Effect = DragDropEffects.Move;
    }

    private void newDGV_DragDrop(object sender, DragEventArgs e)
    {
    if (e.Data.GetDataPresent(typeof(string)))
    {
    string str = (string)e.Data.GetData(typeof(string));
    var record = stuList.FirstOrDefault(a => a.Name.Equals(str));
    stuList.Remove(record);
    newList.Add(record);
    defaultDGV.DataSource = newDGV.DataSource = null;
    defaultDGV.DataSource = stuList;
    newDGV.DataSource = newList;
    }
    }
You better known about the events used above. At the last, in DragDrop event remove the selected record from stuList and add that in newList. And then bind both lists to respective datagridview.

Run the project, defaultDGV have three rows added above, perform your drag-n-drop operation, it will successfully move the record.

Moving Records from a DataGridView to Another in C#: WinForms

Moving Records from a DataGridView to Another in C#: WinForms


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
© Copyright 2013 Computer Programming | All Right Reserved