Showing posts with label winform. Show all posts
Showing posts with label winform. Show all posts

Saturday, November 3, 2012

Array

In computer memory every byte is an array element. Abstractions translate these bytes into objects and give them meaning. Arrays are a foundational type. They are the basis of more usable collections. They use a special syntax form.
An array is a fixed collection of same-type data that are stored contiguously and that are accessible by an index
Arrays are the simplest and most common type of structured data.
Example
As an introduction, let's look at a program that allocates and initializes an integer array of three elements. Please notice how the elements can be assigned to or read from using the same syntax. The array is zero-based.
Program that uses an array [C#]
using System;
class Program
{
static void Main()
{
// Use an array. int[] values = new int[3]; values[0] = 5; values[1] = values[0] * 2; values[2] = values[1] * 2;
foreach (int value in values)
{
Console.WriteLine(value);
}
}
}
Output
5 10 20
Example 2
There is another way to allocate an array and fill it with values. You can use the curly brackets { } to assign element values in one line. The length of the array is automatically determined when you compile your program.
Program that uses another array syntax [C#]
using System;
class Program {
static void Main()
{
// Create an array of three ints.
int[] array = { 10, 30, 50 };
foreach (int value in array)
{
Console.WriteLine(value);
}
}
}
Output
10
30
50
For-loop Sometimes it is useful to use the for-loop construct instead of the foreach-loop on your arrays. This is because it allows you to access the index value (i) as well as the element value in the array.
For example, you could add logic that performs a different computation on the second element (where i == 1). The Length property is necessary here. The for-loop is also helpful for comparing adjacent elements.
Program that uses for loop on int array [C#]
using System;
class Program
{ static void Main()
{
// Create an array of three ints. int[] array = { 100, 300, 500 };
// Use for loop.
for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }
Output
100 300 500
String array Arrays are not just for value types such as ints. They can be used for strings and other object references (classes). An interesting point here is that the strings themselves are not stored in the array.
Rather: Just a reference to the string data is in the array. The strings are typically stored in the managed heap. String Array
Program that creates string array [C#]
using System;
class Program
{ static void Main()
{
// Create string array of four references.
string[] array = new string[4]; array[0] = "DOT"; array[1] = "NET"; array[2] = "PERLS"; array[3] = 2010.ToString();
// Display. foreach (string value in array) { Console.WriteLine(value); } } }
Output
DOT NET PERLS 2010
Parameter How can you pass an array to another method to use there? This example program shows the correct syntax for passing an int array. Please note that the entire contents of the array are not copied.
Instead: Just a reference to the array is copied when the new method is put on the call stack.
Program that receives array parameter [C#]
using System;
class Program {
static void Main()
{ // Three-element array.
int[] array = { -5, -6, -7 };
// Pass array to Method. Console.WriteLine(Method(array)); }
/// <summary> /// Receive array parameter. /// </summary> static int Method(int[] array) {
return array[0] * 2;
}
}
Output
-10
Return array You can return arrays from methods. In this example program, we allocate a two-element array of strings in Method(). Then, after assigning its elements, we return it. In the Main method, the results are displayed.
Program that returns array reference [C#]
using System;
class Program {
static void Main()
{ // Write array from Method. Console.WriteLine(string.Join(" ", Method()));
}
/// <summary> /// Return an array. /// </summary>
static string[] Method() {
string[] array = new string[2]; array[0] = "THANK";
array[1] = "YOU"; return array;
}
}
Output
THANK YOU
2D arrays The C# language offers two-dimensional and multidimensional arrays. These articles provide examples of 2D arrays and also a three-dimensional array. You can loop over 2D arrays or even use them with enumerators. 2D Array 2D Array Loop Multidimensional Array Jagged arrays Jagged arrays are arrays of arrays. They can be faster or slower than 2D arrays based on how you use them. They can also require more or less memory, depending on the shape of your data. Jagged Array Jagged Array Memory First element The first element is at index 0. It can be accessed by using the indexer syntax, which has square brackets. We first ensure that it can be accessed in the array region. We usually test against null and often test the Length.
Program that gets first array element [C#]
using System;
class Program {
static void Main() {
int[] array = new int[2];
// Create an array.
array[0] = 10; array[1] = 20;
Test(array); Test(null); // No output Test(new int[0]); // No output }
static void Test(int[] array) {
if (array != null && array.Length > 0)
{
int first = array[0]; Console.WriteLine(first);
}
} }
Output
10
Last element Next, the last element's offset is equal to the array Length minus one. In many cases you need to remember to check against null and that the Length is greater than zero before accessing the last element.
Program that gets last array element [C#]
using System;
class Program {
static void Main()
{
string[] arr = new string[]
{
"cat", "dog", "panther", "tiger" }; // Get the last string element. Console.WriteLine(arr[arr.Length - 1]);
}
}
Output
tiger
Types We present examples of arrays used with different types available in the C# language. Additionally we see examples of arrays that are static or null. These examples illustrate specific types of arrays. Bool Array Byte Array Char Array Enum Array Int Array Null Array Static Array Array Property Random Byte Array Operations What should you do if you need to combine, flatten or initialize arrays in a certain way? These tutorials can help you out. They provide examples for these requirements. Please also see the Buffer type. Initialize Combine Flatten Initialize Array Methods The Array type introduces many different methods you can use to manipulate or test arrays and their elements. We cover specific methods and provide concrete examples for their usage. Array.AsReadOnly Array.BinarySearch Array.Clear Array.ConstrainedCopy Array.ConvertAll Array.Copy Array.CreateInstance Array.Exists Array.Find Array.FindIndex Array.ForEach Array.IndexOf Array.LastIndexOf Array.Resize Array.Reverse Array.Sort Array. TrueForAll Properties Continuing on, we examine properties on the Array type. The most commonly used property on arrays is the Length property, which is covered in detail here. We also describe the other boolean properties. Array Length Property Count Array Elements Array IsFixedSize, IsReadOnly and IsSynchronized ArraySegment When we use arrays, we often want to read or write into the elements with indexes. The ArraySegment type is an abstraction for a part of an array. With the properties of ArraySegment, we also access the original array. ArraySegment Buffer Buffer efficiently deals with bytes in large arrays. This program uses the Buffer.BlockCopy method. We copy the first 12 bytes (three integers of four bytes each) of the source array (src) into the destination array (dst). Buffer
Tip: You can see that the Buffer type acts upon bytes, not array elements. It is not helpful with object data.
Program that uses Buffer class [C#]
using System;
class Program {
static void Main() {
int[] src = { 1, 2, 3 };
int[] dst = { 0, 0, 0 }; Buffer.BlockCopy(src, 0, dst, 0, 3 * sizeof(int)); foreach (int val in dst) { Console.WriteLine(val); } } }
Output
1 2 3
Performance Arrays are one of the low-level managed types in the C# language and .NET Framework. This means they will be faster than other structures such as List in many cases. We analyze the array type's performance.
1. Avoid loops. You can sometimes avoid using a loop to store or load array elements. This sometimes improves performance. Optimization Tip
2. Use sentinels. A sentinel value in an array helps control the loop. It sometimes is used to reduce logical steps in a loop. Sentinel Element
3. Improve locality. Array elements that are nearer together are faster to access. This principle is called locality of reference. Locality of Reference Summary We reviewed arrays. A

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

Thursday, November 1, 2012

Custom Listview with combox and text box






-->
* ListViewEx.cs
 * This file contains the definition of the class ListViewEx, which is a
 * reusable class derived from ListView.
*/

using System;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Data;

namespace CustomListView
{
/// <summary>
/// Class derived from ListView to give ability to display controls
/// like TextBox and Combobox
/// </summary>
public class ListViewEx : ListView
{

/// <summary>
/// This struct type will be used as the oupput
/// param of the SendMessage( GetSubItemRect ).
/// Actually it is a representation for the strucure
/// RECT in Win32
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}



/// <summary>
/// Summary description for Win32.
/// </summary>
internal class Win32
{
/// <summary>
/// This is the number of the message for getting the sub item rect.
/// </summary>
public const int LVM_GETSUBITEMRECT  = (0x1000) + 56;

/// <summary>
/// As we are using the detailed view for the list,
/// LVIR_BOUNDS is the best parameters for RECT's 'left' member.
/// </summary>
public const int LVIR_BOUNDS = 0;

/// <summary>
/// Sending message to Win32
/// </summary>
/// <param name="hWnd">Handle to the control</param>
/// <param name="messageID">ID of the message</param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", SetLastError=true)]
public static extern int SendMessage(IntPtr hWnd, int messageID, int wParam , ref RECT lParam);
}



/// <summary>
/// This class is used to represent
/// a listview subitem.
/// </summary>
internal class SubItem
{
/// <summary>
/// Item index
/// </summary>
public readonly int row;

/// <summary>
/// Subitem index
/// </summary>
public readonly int col;

/// <summary>
/// Parameterized contructor
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
public SubItem( int row, int col )
{
this.row = row;
this.col = col;
}
}



/// <summary>
/// If this variable is true, then
/// subitems for an item is added
/// automatically, if not present.
/// </summary>
private bool addSubItem = false;
public bool AddSubItem
{
set
{
this.addSubItem = value;
}
}

/// <summary>
/// This variable tells whether the combo box
/// is needed to be displayed after its selection
/// is changed
/// </summary>
private bool hideComboAfterSelChange = false;
public bool HideComboAfterSelChange
{
set
{
this.hideComboAfterSelChange = value;
}
}

/// <summary>
/// Represents current row
/// </summary>
private int row = -1;

/// <summary>
/// Represents current column
/// </summary>
private int col = -1;

/// <summary>
/// Textbox to display in the editable cells
/// </summary>
private TextBox textBox = new TextBox();

/// <summary>
/// Combo box to display in the associated cells
/// </summary>
private ComboBox combo = new ComboBox();

/// <summary>
/// This is a flag variable. This is used to determine whether
/// Mousebutton is pressed within the listview
/// </summary>
private bool mouseDown = false;

/// <summary>
/// To store, subitems that contains comboboxes and text boxes
/// </summary>
private Hashtable customCells = new Hashtable();



/// <summary>
/// Constructor
/// </summary>
public ListViewEx()
{
// Initialize controls
this.InitializeComponent();
}

/// <summary>
/// Initializes the text box and combo box
/// </summary>
private void InitializeComponent()
{
// Text box
this.textBox.Visible = false;
textBox.BorderStyle = BorderStyle.FixedSingle;
this.textBox.Leave += new EventHandler(textBox_Leave);

// Combo box
this.combo.Visible = false;
this.Controls.Add( this.textBox );
this.Controls.Add( this.combo );
this.combo.DropDownStyle = ComboBoxStyle.DropDownList;
this.combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);

            this.combo.SelectedIndexChanged -= new EventHandler(combo_SelectedIndexChanged);
}

/// <summary>
/// This method will send LVM_GETSUBITEMRECT message to
/// get the current subitem bouds of the listview
/// </summary>
/// <param name="clickPoint"></param>
/// <returns></returns>
private RECT GetSubItemRect(Point clickPoint)
{
// Create output param
RECT subItemRect = new RECT();

// Reset the indices
this.row = this.col = -1;

// Check whether there is any item at the mouse point
ListViewItem item = this.GetItemAt(clickPoint.X, clickPoint.Y);

if(item != null )
{
for(int index = 0; index < this.Columns.Count; index++)
{                                
// We need to pass the 1 based index of the subitem.
subItemRect.top = index + 1;

// To get the boudning rectangle, as we are using the report view
subItemRect.left = Win32.LVIR_BOUNDS;
try
{
// Send Win32 message for getting the subitem rect.
// result = 0 means error occuured
int result = Win32.SendMessage(this.Handle, Win32.LVM_GETSUBITEMRECT, item.Index, ref subItemRect);
if( result != 0 )
{
// This case happens when items in the first columnis selected.
// So we need to set the column number explicitly
if(clickPoint.X < subItemRect.left)
{
this.row = item.Index;
this.col= 0;
break;
}
if(clickPoint.X >= subItemRect.left & clickPoint.X <=
subItemRect.right)
{
this.row = item.Index;
// Add 1 because of the presence of above condition
this.col = index + 1;
break;
}
}
else
{
// This call will create a new Win32Exception with the last Win32 Error.
throw new Win32Exception();
}
}
catch( Win32Exception ex )
{
Trace.WriteLine( string.Format("Exception while getting subitem rect, {0}", ex.Message ));
}
}
}                        
return subItemRect;
}

/// <summary>
/// Set a text box in a cell
/// </summary>
/// <param name="row">The 0-based index of the item.  Give -1 if you
///                                          want to set a text box for every items for a
///                                          given "col" variable.
///        </param>
/// <param name="col">The 0-based index of the column. Give -1 if you
///                                          want to set a text box for every subitems for a
///                                          given "row" variable.
///        </param>
public void AddEditableCell( int row, int col )
{
// Add the cell into the hashtable
// Value is setting as null because it is an editable cell
this.customCells[new SubItem( row, col )] = null;
}

/// <summary>
/// Set a combobox in a cell
/// </summary>
/// <param name="row"> The 0-based index of the item.  Give -1 if you
///                                           want to set a combo box for every items for a
///                                           given "col" variable.
///        </param>
/// <param name="col"> The 0-based index of the column. Give -1 if you
///                                           want to set a combo box for every subitems for a
///                                           given "row" variable.
///        </param>
/// <param name="data"> Items of the combobox
/// </param>
public void AddComboBoxCell( int row, int col, StringCollection data )
{
// Add the cell into the hashtable
// Value for the hashtable is the combobox items
this.customCells[new SubItem( row, col )] = data;
}

/// <summary>
/// Set a combobox in a cell
/// </summary>
/// <param name="row"> The 0-based index of the item.  Give -1 if you
///                                           want to set a combo box for every items for a
///                                           given "col" variable.
///        </param>
/// <param name="col"> The 0-based index of the column. Give -1 if you
///                                           want to set a combo box for every subitems for a
///                                           given "row" variable.
///        </param>
/// <param name="data"> Items of the combobox
/// </param>
public void AddComboBoxCell( int row, int col,DataTable data)
{
try
{
StringCollection param = new StringCollection();
                for (int i = 0; i < data.Rows.Count; i++)
                    param.Add(data.Rows[i]["Name"].ToString());
this.AddComboBoxCell( row, col, param );
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

/// <summary>
/// This method will display the combobox
/// </summary>
/// <param name="location">Location of the combobox</param>
/// <param name="sz">Size of the combobox</param>
/// <param name="data">Combobox items</param>
private void ShowComboBox( Point location, Size sz, StringCollection data )
{
try
{
// Initialize the combobox
combo.Size = sz;
combo.Location = location;
// Add items
combo.Items.Clear();
foreach( string text in data )
{
combo.Items.Add( text );
}                        
// Set the current text, take it from the current listview cell
combo.Text = this.Items[row].SubItems[col].Text;
// Calculate and set drop down width
combo.DropDownWidth = this.GetDropDownWidth(data);
// Show the combo
combo.Show();
}
catch( ArgumentOutOfRangeException )
{
// Sink
}
}

/// <summary>
/// This method will display the textbox
/// </summary>
/// <param name="location">Location of the textbox</param>
/// <param name="sz">Size of the textbox</param>
private void ShowTextBox( Point location, Size sz )
{
try
{
// Initialize the textbox
textBox.Size = sz;
textBox.Location = location;
// Set text, take it from the current listview cell
textBox.Text = this.Items[row].SubItems[col].Text;
// Shopw the text box
textBox.Show();
textBox.Focus();
}
catch( ArgumentOutOfRangeException )
{
// Sink
}
}

/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp ( MouseEventArgs e)
{
try
{
// Hide the controls
this.textBox.Visible = this.combo.Visible = false;

// If no mouse down happned in this listview,
// no need to show anything
if( !mouseDown )
{
return;
}

// The listview should be having the following properties enabled
// 1. FullRowSelect = true
// 2. View should be Detail;
if( !this.FullRowSelect || this.View != View.Details )
{
return;
}

// Reset the mouse down flag
mouseDown = false;

// Get the subitem rect at the mouse point.
// Remeber that the current row index and column index will also be
// Modified within the same method
RECT rect = this.GetSubItemRect( new Point( e.X, e.Y ));

// If the above method is executed with any error,
// The row index and column index will be -1;
if( this.row != -1 && this.col != -1 )
{
// Check whether combobox or text box is set for the current cell
SubItem cell = GetKey(new SubItem(this.row, this.col ));

if( cell != null)
{
// Set the size of the control(combobox/editbox)
// This should be composed of the height of the current items and
// width of the current column
Size sz = new Size(this.Columns[col].Width, Items[row].Bounds.Height );

// Determine the location where the control(combobox/editbox) to be placed
Point location = col == 0 ? new Point(0, rect.top) : new Point( rect.left, rect.top);

ValidateAndAddSubItems();

// Decide which conrol to be displayed.
if(this.customCells[cell] == null )
{
this.ShowTextBox( location, sz );
}
else
{
this.ShowComboBox( location, sz, (StringCollection) this.customCells[cell] );
}
}
}
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

/// <summary>
///
/// </summary>
private void ValidateAndAddSubItems()
{
try
{
while( this.Items[this.row].SubItems.Count < this.Columns.Count && this.addSubItem )
{
this.Items[this.row].SubItems.Add("");
}
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

/// <summary>
/// This message will get the largest text from the given
/// stringarray, and will calculate the width of a control which
/// will contain that text.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private int GetDropDownWidth( StringCollection data )
{
// If array is empty just return the combo box width
if( data.Count == 0 )
{
return this.combo.Width;
}

// Set the first text as the largest
string maximum = data[0];

// Now iterate thru each string, to findout the
// largest
foreach( string text in data )
{
if( maximum.Length <  text.Length )
{
maximum = text;
}
}
// Calculate and return the width .
return (int)(this.CreateGraphics().MeasureString( maximum , this.Font ).Width);
}

/// <summary>
/// For this method, we will get a Subitem.
/// Then we will iterate thru each of the keys and will
/// check whther any key contains the given cells row/column.
/// If it is not found we will check for -1 in any one
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private SubItem GetKey( SubItem cell )
{
try
{
foreach( SubItem key in this.customCells.Keys )
{
// Case 1: Any particular cells is  enabled for a control(Textbox/combobox)
if( key.row == cell.row && key.col == cell.col )
{
return key;
}
// Case 2: Any particular column is  enabled for a control(Textbox/combobox)
else if( key.row == -1 && key.col == cell.col )
{
return key;
}
// Entire col for a row is is  enabled for a control(Textbox/combobox)
else if( key.row == cell.row && key.col == -1 )
{
return key;
}
// All cells are enabled for a control(Textbox/combobox)
else if( key.row == -1 && key.col == -1 )
{
return key;
}
}
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
return null;
}

/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
try
{
// Mouse down happened inside listview
mouseDown = true;

// Hide the controls
this.textBox.Hide();
this.combo.Hide();
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

/// <summary>
/// This event handler wll set the current text in the textbox
/// as the listview's current cell's text, while the textbox
/// focus is lost
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox_Leave(object sender, EventArgs e)
{
try
{
if( this.row != -1 && this.col != -1 )
{
this.Items[row].SubItems[col].Text = this.textBox.Text;
this.textBox.Hide();
}
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

/// <summary>
/// This event handler wll set the current text in the combobox
/// as the listview's current cell's text, while the combobox
/// selection is changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void combo_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if( this.row != -1 && this.col != -1 )
{
this.Items[row].SubItems[col].Text = this.combo.Text;
this.combo.Visible = !this.hideComboAfterSelChange;                
}
}
catch( Exception ex )
{
Trace.WriteLine( ex.ToString());
}
}

}
}


Form.cs

using CustomListView;

private ListViewEx listViewMain;
 private void Form1_Load(object sender, System.EventArgs e)
        {
            // If subitem is not added, add it automatically on clicking an item.
            this.listViewMain.AddSubItem = true;

            // Make the Name and adress columns editable
            this.listViewMain.AddEditableCell(-1, 0);
            this.listViewMain.AddEditableCell(-1, 2);

            // Create data for combobox
            StringCollection grades = new StringCollection();
            grades.AddRange(new string[] { "A", "B", "C", "D", "E" });

            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Value");
            DataRow dr = dt.NewRow();
            dr["Name"] = "Sanjay";
            dr["Value"] = "1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr["Name"] = "Raju";
            dr["Value"] = "2";
            dt.Rows.Add(dr);

            // Set the combobox
            this.listViewMain.AddComboBoxCell(-1, 1, dt);
        }



If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

Wednesday, October 31, 2012

Bind combobox in datagridview in editable mode in winform

 I want editable grid in my project, I  do this as below using"  dataGridView1_EditingControlShowing" event.







using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DataGridViewComboBoxBinding
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.dataGridView1.AutoGenerateColumns = false;
            this.ColumnPersonTypeCode.DataPropertyName = "Value";
            this.ColumnPersonTypeCode.DisplayMember = "Name";
            this.ColumnPersonTypeCode.ValueMember = "Value";
            this.ColumnPersonTypeCode.DataSource = Findingproduct();
            //this.dataGridView1.DataSource = Findingproduct();
            //Findingproduct();
        private DataTable Findingproduct()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Value");
            DataRow dr = dt.NewRow();
            dr[0] = "sanjay";
            dr[1] = "1";
            dt.Rows.Add(dr);

            dr = dt.NewRow();
            dr[0] = "Raju";
            dr[1] = "2";
            dt.Rows.Add(dr);

            return dt;
        }

        void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (this.dataGridView1.CurrentCell.ColumnIndex == this.ColumnPersonTypeCode.Index)
            {
              //BindingSource bindingSource = this.dataGridView1.DataSource as BindingSource;
        }
              // Person person = bindingSource.Current as Person;
              //BindingList<PersonType> bindingList = this.FindPersonTypes(person);

                DataGridViewComboBoxEditingControl comboBox = e.Control as DataGridViewComboBoxEditingControl;
                DataGridViewTextBoxEditingControl txt=e.Control as DataGridViewTextBoxEditingControl;
                //comboBox.DataSource = Findingproduct();

                comboBox.SelectionChangeCommitted -= this.comboBox_SelectionChangeCommitted;
                comboBox.SelectionChangeCommitted += this.comboBox_SelectionChangeCommitted;
            }
        }

        void comboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            var currentcell = dataGridView1.CurrentCellAddress;
            var sendingCB = sender as DataGridViewComboBoxEditingControl;
            DataGridViewTextBoxCell cel = (DataGridViewTextBoxCell)dataGridView1.Rows[currentcell.Y].Cells[0];
            cel.Value = sendingCB.EditingControlFormattedValue.ToString();

            this.dataGridView1.EndEdit();
        }

       
    }

  
}

After Run Result  window:





Label :winform ,c#,asp.net,combobox,datagridview

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website