-->

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.

Tuesday, November 5, 2013

How to Provide Search Feature in DataGridView: Windows Forms

We have successfully bind our datagridview with a list of items discussed in earlier post. What if there are many records in our list and datagridview is looking full of records. In this case, user can’t even search any single record, if he/she find, it will be a time consuming process.

So we (The Programmer) have to provide a search feature, through which the user can find some records according to the desired condition. A textbox have its TextChanged event that is triggered when the text value of the textbox is changed. So our task is to write some code in this event, so that when user change the text, the datagridview vary according to the code.

Create a list and bind a datagridview with that list. Add a textbox in the form and generate its TextChanged event and write the following code as it is.
private void searchTextBox_TextChanged(object sender, EventArgs e)
{
if (searchTextBox.Text != string.Empty)
{
var searchResult = stuList.Where(a => a.Name.StartsWith(searchTextBox.Text));
dataGridView1.DataSource = searchResult.ToList();
}
else
dataGridView1.DataSource = stuList;
}

The code will search all the records that’s name will be starts with the given text in the searchTextBox. The following image shows the result after write the character “B” in the textbox. Only a single record will be shown because there is only a single record in the list.

How to provide search feature in DataGridView: Windows Forms

Now if we don’t know the starting characters of the name then there is another function i.e. Contains() that can be used to search all the records that contains the text. Just replace the first line with the below line.

var searchResult = stuList.Where(a => a.Name.Contains(searchTextBox.Text));

Run the project and write the character “o” in the textbox and it will show the result in datagridview as shown:

How to provide search feature in DataGridView: Windows Forms

The datagridview binding will vary with the text changed in the textbox, and if the textbox left empty then it will show all the records of the list.

Friday, November 1, 2013

How to Access Record by DataGridViewButton: Windows Forms

I have created a DataGridViewButton for each particular record of DataGridView, as in my earlier post. Adding a button is not sufficient in programming, it should perform some functions when clicked, so we have to generate its click event.

In simple words, we can’t generate a click event of this DataGridViewButton using double click or from the events section. As this is in datagridview so generate Cell_Click event of this datagridview. Now, I have added this button in first column, so I can check it on the same.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("Column: " + e.ColumnIndex + " and Row: " + e.RowIndex);
}

By this simple code, the debugger will execute all your line of code, written in the space provided. ColumnIndex contains the column index and RowIndex contains row index, when this event triggered.

Let suppose, we want to access the record of the clicked row of datagridview. I have bound that datagridview with list of student class, so the following C# lines of code will get the instance of student, which is currently focused by mouse click event.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Student stu = dataGridView1.Rows[e.RowIndex].DataBoundItem as Student;
MessageBox.Show("Name: " + stu.Name + "\r" + "Age: " + stu.Age
+ "\r" + "City" + stu.City + "\r"
+ "Dob: " + stu.Dob);
}

The first line will get the particular record, which is of student type. When we run the project and click on the datagridviewbutton it will show a message box, containing the detail of particular student.

How to access record by Datagridviewbutton in C#: Windows Forms

Thursday, October 31, 2013

How to Add Commands with Binding in DataGridView: Windows Forms

After binding records with DataGridView, there may be some options to edit or to remove those records. To do these simple task we can provide either a button, which gets the selected record and perform operation, or we can provide the button with each particular record.

We will discuss here how to add a button with particular record with the following simple steps. Drag-n-drop a datagridview on the form and a task pop-up menu will automatically open, click on Add Columns link button to add a new column. It will show following Add Column window.

How to Add Commands with Binding in DataGridView: Windows Forms

By default Unbound column radio button have been checked, if not check it and use the following values in respective fields:
  • Type: DataGridViewButtonColumn
  • Header Text: Command (Changeable)
Sure the Visible check box is checked and click on Add button to add this column. Now you have successfully added a command button with empty text as shown in below image:

How to Add Commands with Binding in DataGridView: Windows Forms

To write text on the button generate Cell_Formatting event of dataGridview and set the value of first column as I do in the following c# code:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[0].Value = "Remove";
}

When you run the project now, it will show “remove” on the button. To check if this code will works for multiple records or not, add some records in data gridview like How to add Records in Datagridview. Run the project now and it will show the Remove button with each record as shown in the following image:

How to Add Commands with Binding in DataGridView: Windows Forms

In the next article I will remove the particular record with this command button.

How to Bind ComboBox with List of Items: C#

A list of items is used to store some temporary records, used in the program and do some operations like sorting, grouping and etc. In the previous post we have created a list and bind that list to the datagridview, using its DataSource property.

A combo box also have DataSource property to bind some data as I have discussed in my earlier article i.e. How to bind combobox with database. Combo Box is used to display a single field at a time and a list can contains multiple fields. I will use the same student class as in my earlier articles.
To show a single field, combo box have a property DisplayMember that will specify the field to display. In the following C# code the student list will bind with the combo box and name field will be shown.

List<Student> stuList = new List<Student>();
cmbBox.DataSource = stuList;
cmbBox.DisplayMember = "Name";

Before running this code, you have to sure that your list have some records to show. It will not throw an exception, but it will also not show any records because the list is empty.

Run the project and combo box will bind the list items and we can select any of them. The image shown the combo box items:

How to bind combobox with list of items: C# Windows forms

Saturday, October 26, 2013

How to Get Selected Fields from List Using LINQ: C#

When we bind a list with a control like datagridview, comboBox or listbox, then it will bind all the fields related to list. I have created a list of student with multiple fields i.e. Name, age, city and DOB. Now in this article I will bind only name and age of this list to a Datagridview.

To get selected fields, syntax of LINQ query will be:
var variable = from tempVar in list
select new
{
   tempVar.Field1,
   tempVar.Field2
};

Now in our case of Student class the records should be selected through the following C# line of code:
var selectedFields = from s in stuList
select new
{
s.Name,
s.Age
};
dataGridView1.DataSource = selectedFields.ToList();

In the last line of code, it will bind the list to gridview and show only name and age of the students like in following image:

Get selected fields in LINQ: C# windows forms
If all the LINQ methods are not showing in your program then sure about the namespace in your code file i.e. System. Linq;

See Also: How to Bind DataGridView with DataSet
© Copyright 2013 Computer Programming | All Right Reserved