-->

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.

Wednesday, September 25, 2013

How to Retrieve Data from SQL Database: Windows Forms

In my previous post, I have created a connection object and then get all the records from the database table. What if we want to bind our datagridview without writing a single line of code? So in this article we will do something like this.


 Just drag-n-drop a datagridview on the form and name it, if you want. A datagridview tasks pop-up menu appears automatically as shown:

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Select the Choose Data Source drop-down list and then Add Project Data Source as shown:

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Now Data Source Configuration wizard will open, select Database as your data source. The wizard will look like:

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

By clicking on Next button, It will prompt for the database model you want to use. Select dataset, it will determines the type of data objects our application will use.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

In the next step we have to choose our connection that is used by the application use to connect to the database.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Click on New Connection and it will prompt for Choose Data Source dialog box having some more options to select.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Select Microsoft SQL Server which is used to connect to MS SQL Server, and the data provider should be .NET Framework Data Provider for SQL Server. Add Connection dialog box will appear as shown:

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Write the server name as given “(LocalDb)\v11.0”, and select appropriate database name from the drop down list below. I have select StockDb here. Just click on Test Connection to check our connection succeeded or not.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Press ok and it will show Data Source Configuration wizard again with the specified connection and also connection string.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

Choose the table name from the tree view shown. I have select Groups table because I want to show the records of groups table. Finish now with selecting the data set name. If you will forget the dataset name, it will used the by default name.

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

It will show the datagridview binding with the columns names of groups table as shown in the above image. Now run the project and look out the records bind to the datagridview

How to Retrieve Data From SQL Server Database and bind to DataGridView in Windows Forms

As I have said above, we have not wrote a single line of code.

Thursday, September 19, 2013

How to Bind DataGridView with DataSet in Windows Forms: ADO.NET

In our previous post, I have described about the ways to bind datagridview in windows forms. The first way is to bind the datagridview with dataset and show the data of a table in the gridview. Here is the syntax of binding in c#:
dataGridView.DataSource= ”DataSet Name”;
dataGridView.DataMember=”Table Name”;

Now the time is to perform this code with our existing dataset and table. Drag-n-drop a datagridview on the window and write the following c# code in our form’s constructor:
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=(LocalDb)\\v11.0; Initial Catalog=StockDb; Integrated Security=True";
connection.Open();

SqlCommand command = new SqlCommand("select * from Groups", connection);

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(ds);

dataGridView1.DataSource = ds;
dataGridView1.DataMember = ds.Tables[0].ToString();

In the above code, first four lines are same as written in executing sql statements. Fifth line will create a new object of DataSet. Six line will create an object of SqlDataAdapter class which will create an adapter with specified command object.

Next line tell us to fill the dataset with the adapter, which contains all the rows returning by the command object.

Now the last two lines are used to specify the data source of datagridview and the table which will be bind to. When we run the code a window will show with a datagridview containing all the returning rows as shown in following image:

How to bind DataGridView with dataset in Windows Forms ADO.NET

Tuesday, September 3, 2013

How to Add Columns in DataGrid Control: WPF

Datagrid is used to represent a tabular view of data in programming. It have multiple template designs to be customizable by the programmer as per the requirements. It supports some other features like sorting the data, dragging columns and sometimes editing when user needs to do.


To add a DataGrid, just drag-n-drop it from the toolbox. Now it is known as a tabular representation, write following code to add some columns (3 here):
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn Header="First Column"/>
<DataGridTextColumn Header="Second Column"/>
<DataGridTextColumn Header="Third Column"/>
</DataGrid.Columns>
</DataGrid>

When we run this window then a Datagrid is shown with three columns like in below image:

How to add columns in DataGrid control in WPF

DataGrid provides columns sorting, reordering and sizing with some properties like CanUserReorderColumns, CanUserResizeColumns, CanUserSortColumns and etc. We can even perform grouping of data by adding a group description for the list to be bind.

To add a datagrid using code behind:
DataGrid dataGrid = new DataGrid();

DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "First Column";
DataGridTextColumn textColumn2 = new DataGridTextColumn();
textColumn2.Header = "Second Column";
DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn3.Header = "Third Column";

dataGrid.Columns.Add(textColumn1);
dataGrid.Columns.Add(textColumn2);
dataGrid.Columns.Add(textColumn3);

The above code snippet add a same datagrid with three columns as in above image. We will learn binding of datagrid in later articles.

Monday, August 19, 2013

Passing Values from DataGridView between Different Forms

Sometimes we need to transfer all the rows and columns of a DataGridView from one form to another. In this article I will transfer all the binded data of first form's grid view and bind them to second form's grid view.

Create two forms with dataGridView in each and a button on first form. Create a class to which your datagridview will bind like i create a student class having Name, Age and address field.
Bind the first form's gridview in C# language as
studList.Add(new Student() { Name = "Jacob", Age = 23, Address = "London" });
studList.Add(new Student() { Name = "Jaklin", Age = 25, Address = "US" });
studList.Add(new Student() { Name = "Julia", Age = 26, Address = "UK" });
dataGridView1.DataSource = studList;

In the click event of button write the following code in C# language
List<Student> tempList = dataGridView1.DataSource as List<Student>;
new Form1(tempList).ShowDialog();

And your second form's constructor have to look like the below code in C# language
public Form1(List<Student> sourceList)
{
InitializeComponent();
dataGridView1.DataSource = sourceList;
}
When we run this project and click on transfer button then both the form have same list of data e.g.

So we have passed all the rows and columns of first form's gridview to second form's gridview.
© Copyright 2013 Computer Programming | All Right Reserved