Tag Archives: DatagridView

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");

Change DataGridView column style at runtime in C#

How to change DataGridview column style at runtime in Visual Studio C#.Net?

Simply get the column from the Gridview with the help of subclass of GridView. The code will look like

DataGridViewComboBoxColumn products = new DataGridViewComboBoxColumn();
products = (DataGridViewComboBoxColumn)dataGridView1.Columns[ITEM.Index];
products.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
products.FlatStyle = FlatStyle.Flat;

All changes made to the object products will change the dataGridView1.Columns[ITEM.Index] since the object point to the dataGridveiw column ITEM.

* It resembles pointers in C, where a value changes in a pointer also reflect the variable.

Ado.Net connection,adapter,dataset and dataview explained

I wrote this post for those who have no idea about C# database connection.

When starting with Visual Studio language like C#/VB.Net, you need to understand the concept of adapter, dataset and data view.

SQL connection

SQL connection class helps you to build the connection string.Visual studio can build connection string for you or  can create your in App config [Solution Explorer]

<add name=”MACCon” connectionString=”Data Source=(LocalDB)\MSSQLlocalDB;AttachDbFilename=e:\Developerm\c# Projects\MAcc_Prime\MAcc\MACCDATA.mdf;Integrated Security=True” />

Use SQL connection object to configure the connection as follows

con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[“MACCon”].ConnectionString;

Now you’re ready to use database

Data Adapter

The data adapter is the bridge between database tables with the application. The Adapter class helps you to the configugure table. The Adapter connects to the database throw the connection object.

geTradp = new SqlDataAdapter(“select dr,cr from accounttransactions where entry=” + mcode + ” and acid=” + acid + ” and tdate>='” + sdate + “‘ and tdate<='” + edate + “‘”, Common.con);

Here “conn” is the SQL database connection object

Dataset and Data Views

DataSet is the local version of your database table, you can work with the dataset and its data even if the connection has closed. Data Set accompanying with command builder also simplifies operation like adding new data, updating /deleting data etc

Dataset can also be used as data source for controls like data grid view.

Data View is a special object which offers table view so that you can fetch columns, rows, filter, extract rows with Find, FindRow methods loops through recordsets with the help subclasses of data view like Data RowView.

Let’s begin with .Net programming




Overriding DataGridView ProcessDataGridViewKey and ProcessDialogKey

The ENTER key behavior of C# application can be customized by overriding ProcessCmdKeyIt will affect all controls in the form if you more than one control.

Our objective is to facilitate the Enter key action for DataGridView only. This can be done with inheriting and customizing the DataGridView.

What we going to do.

  1. Add C# Windows Form Application Project
  2. Add DataGridView control and also add some columns
  3. Then we inherit a new class
  4. Replacing the designer class declaration

Customizing the DataGridView Class

  • Inheriting a new class from DataGridView class
  • Overriding ProcessDialogKey which handle dialog characters, such as TAB, RETURN, ESCAPE, and arrow keys
  • Overriding Processes keys which is used for navigating in the DataGridView

 The new DataGridView

public class CustomDataGridView : DataGridView
Window = System.Security.Permissions.UIPermissionWindow.AllWindows)]

protected override bool ProcessDialogKey(Keys keyData)
// Extract the key code from the key value.
Keys key = (keyData & Keys.KeyCode);
// Handle the ENTER key as if it were a RIGHT ARROW key.
if (key == Keys.Enter)
return this.ProcessRightKey(keyData);
return base.ProcessDialogKey(keyData);
System.Security.Permissions.SecurityAction.LinkDemand, Flags =
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
// Handle the ENTER key as if it were a RIGHT ARROW key.
if (e.KeyCode == Keys.Enter)
if (base.CurrentCell.ColumnIndex == 9)
int cri = base.CurrentRow.Index;
base.CurrentCell = base.Rows[cri + 1].Cells[0];
catch(System.ArgumentOutOfRangeException error)
base.CurrentCell = base.Rows[cri + 1].Cells[0];
return ProcessRightKey(e.KeyData);

return base.ProcessDataGridViewKey(e);

Replacing the Form.DataGridView

Now we are ready to replace the system defined DataGridView with customized one.
Find the YourFom.Designer.cs file

Replace default object
this.dataGridView1 = new System.Windows.Forms.DataGridView();
private System.Windows.Forms.DataGridView dataGridView1
private CustomDataGridView dataGridView1;
this.dataGridView1 = new CustomDataGridView ();

Let’s Run and see what is happening. Enter key will take you next column and when you reach 10th column it will add a new row only if there are no more rows, which we made possible with catch section.

I hope this will work fine as mine.

Source : Codehat3

C# – Change Default “Enter” Key Behavior In DataGridView to left to right

As we know DataGridView in C# act quite differently with Enter key. When user pressed the Enter key it will take them to next row instead of next column.  For more convenient data entry require left to right movement not top to bottom . C#.Net has ability to change the default behavior of the enter key.

This can be done with overriding the processcmdKey method.

This will change Enter key behavior on the form itself. If you have any code to move focus to other controls it may fail

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)


// Check if Enter is pressed

if (keyData == Keys.Enter)




if (dataGridView1.CurrentCell.ColumnIndex == 9)


dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index + 1].Cells[1];

return true;




SendKeys.Send(“{right }”);



catch (Exception e)



dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.CurrentRow.Index ].Cells[1];



return true;


return base.ProcessCmdKey(ref msg, keyData);


add the above overriding section to the end of the class methods. The Catch method check for the error when there are no rows and add a new row, focus the column.

The original post which help me to solve the problem can be found on inforbiro.com


Autocomplete text to a single datagridview column in C#

We already discussed the matter how to suggest AutoComplte Text  for datagridview column in C#. This post is the extension to that post, which will explain , limit the searching capability for single column.

Task: Need Autocomplete suggest list of Text as I type for the PARTY column only[DataGridView].


Drop the following code in the  dataGridView1_EditingControlShowing event.

TextBox auto = e.Control as TextBox;
 if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].HeaderText == "PARTY")
 AutoCompleteStringCollection autotxt = new AutoCompleteStringCollection();

foreach (DataRowView row in Common.AccountRegistrationTableView)
 auto.AutoCompleteMode = AutoCompleteMode.Suggest;
 auto.AutoCompleteSource = AutoCompleteSource.CustomSource;
 auto.AutoCompleteCustomSource = autotxt;
 auto.AutoCompleteMode = AutoCompleteMode.None;
 auto.AutoCompleteSource = AutoCompleteSource.None;
 auto.AutoCompleteCustomSource = null;

  • Firstly  capture the control using TextBox auto = e.Control as TextBox;
  • Secondly  populate names from the database and add to AutocompletStringCollection.
  • Thirdly  attach the collection to custom source of the control.
  • The else part simply prevent from displaying autocomplete for every columns in the datagridview.