ComboBox with DataGridView in C#

Using ComboBox with DataGridView is not that complex anymore but it’s almost mandatory while doing some data driven software development.

I have created a DataGridView like this one. Now, I want to show “Month” and “Item” instead of “MonthID” and “ItemID” in DataGridView.

            //Item Data Source

            string selectQueryStringItem= "SELECT ItemID,ItemText FROM Table_Item";

            SqlDataAdapter sqlDataAdapterItem = new SqlDataAdapter(selectQueryStringItem, sqlConnection);
            SqlCommandBuilder sqlCommandBuilderItem = new SqlCommandBuilder(sqlDataAdapterItem);

            DataTable dataTableItem = new DataTable();
            sqlDataAdapterItem.Fill(dataTableItem);
            BindingSource bindingSourceItem = new BindingSource();
            bindingSourceItem.DataSource = dataTableItem;

            //Month Data Source

            string selectQueryStringMonth = "SELECT MonthID,MonthText FROM Table_Month";

            SqlDataAdapter sqlDataAdapterMonth = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
            SqlCommandBuilder sqlCommandBuilderMonth = new SqlCommandBuilder(sqlDataAdapterMonth);

            DataTable dataTableMonth= new DataTable();
            sqlDataAdapterMonth.Fill(dataTableMonth);
            BindingSource bindingSourceMonth = new BindingSource();
            bindingSourceMonth.DataSource = dataTableMonth;

Let’s start with preparing DataSource for “Item” and “Month” ComboBox.

            //Adding  Month Combo

            DataGridViewComboBoxColumn ColumnMonth = new DataGridViewComboBoxColumn();

            ColumnMonth.DataPropertyName = "MonthID";

            ColumnMonth.HeaderText = "Month";
            ColumnMonth.Width = 120;

            ColumnMonth.DataSource = bindingSourceMonth;
            ColumnMonth.ValueMember = "MonthID";
            ColumnMonth.DisplayMember = "MonthText";

		dataGridViewComboTrial.Columns.Add(ColumnMonth);


            //Adding  Year TextBox

            DataGridViewTextBoxColumn ColumnYear = new DataGridViewTextBoxColumn();
            ColumnYear.HeaderText = "Year";
            ColumnYear.Width = 80;
            ColumnYear.DataPropertyName = "Year";
		
		dataGridViewComboTrial.Columns.Add(ColumnYear);

Set the “DataSource” and most importantly set the “DataPropertyName” accurately for “ColumnMonth” .

            //Adding  Item ComboBox

            DataGridViewComboBoxColumn ColumnItem = new DataGridViewComboBoxColumn();
            ColumnItem.DataPropertyName = "ItemID";
            ColumnItem.HeaderText = "Item";
            ColumnItem.Width = 120;

            ColumnItem.DataSource = bindingSourceItem;
            ColumnItem.ValueMember = "ItemID";
            ColumnItem.DisplayMember = "ItemText";

            dataGridViewComboTrial.Columns.Add(ColumnItem);

            //Adding  Year TextBox

            DataGridViewTextBoxColumn ColumnSaleAmount = new DataGridViewTextBoxColumn();
            ColumnSaleAmount.HeaderText = "Total Sale";
            ColumnSaleAmount.Width = 120;
            ColumnSaleAmount.DataPropertyName = "SaleAmount";

            dataGridViewComboTrial.Columns.Add(ColumnSaleAmount);

            //Adding  Remarks TextBox

            DataGridViewTextBoxColumn ColumnSaleRemarks = new DataGridViewTextBoxColumn();
            ColumnSaleRemarks.HeaderText = "Remarks";
            ColumnSaleRemarks.Width = 150;
            ColumnSaleRemarks.DataPropertyName = "Remarks";

            dataGridViewComboTrial.Columns.Add(ColumnSaleRemarks);


Set the “DataSource” and “DataPropertyName” for “ColumnItem” .

     public partial class DataGridViewComboForm : Form
     {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataGridViewComboForm()
        {
            InitializeComponent();
        }

        private void DataGridViewComboForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();

            //DataGridView Source

            selectQueryString = "SELECT * FROM Table_SaleSummary";
                        
            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

Prepare DataSource For your DataGridView.

            //Setting Data Source for DataGridView

            dataGridViewComboTrial.DataSource = bindingSource;

Finally, set DataSource for the DataGridView and get your expected output the following one.

        private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridViewComboTrial.Rows.RemoveAt(dataGridViewComboTrial.CurrentRow.Index);
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }

        }

This above code snippet will enable user to insert, update or delete Row in Database directly at Button Click Events. Download Sourcecode here.

Thanks
A Rahim Khan

About these ads
    • Mohamed
    • August 7th, 2010

    Well Written Mr. Khan,

    Question, how would you remove an item from the drop down list in the datagridview combo box AFTER the user has selected it.

    i.e: i have 3 cars (Toyota,Bmw,Merc) in a datagridview.combobox list. In row 1 i selected Toyota,
    in Row two when the user drops down the list, toyota SHOULD NOT BE DISPLAYED, how can i acheive this?

    Moahmed

    • Hey Mohamed, thanks for appreciation.

      I have not gone through the kind of situation before. You can remove the selected item at DropDownList Click Event from DropDownList Data Source and reassign it to DropDownList. I hope this will serve the your purpose. I will look into this issue again and let you know.

      • removing selected item from Data Source is not a good idea. You can stop user selecting the same twice.

        Have a look at those events.

        private void dataGridViewComboTrial_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
        if (e.ColumnIndex == 0)
        {
        latestSelection = Convert.ToInt16(dataGridViewComboTrial.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) – 1;
        if (SelectedUptoThis.Contains(latestSelection) == true)
        {
        MessageBox.Show(“You can not select it again”);
        dataGridViewComboTrial.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
        QuestionEventArgs e1 = new QuestionEventArgs();
        this.dataGridViewComboTrial_CancelRowEdit(sender, e1);
        }
        else
        {
        SelectedUptoThis.Add(latestSelection);
        }
        }
        }

        private void dataGridViewComboTrial_CancelRowEdit(object sender, QuestionEventArgs e)
        {
        e.Response = true;
        }

    • Jamal
    • January 4th, 2011

    Thank you very much for your cooperation.I used your code but I want to find data in combo by filtering another combo.Please help me.

    • sara
    • February 4th, 2011

    hi dear
    thank you.

    • omid_poyan
    • June 5th, 2011

    many many thanks this code very great,hope so you bring all things you want.

    so thanks

    • maryam
    • September 11th, 2011

    thanks alot .
    Your cod is so usefull for me.
    please help me about this problem
    How do I change value (or access selected index) combobox in datagridview
    I ‘m waiting for your fast reply
    thank you

    • Ajay
    • October 21st, 2011

    hii it is for two values only..
    what if after 2 3 selection user again selected the previously selected value, if we want to bann this then how to do it…

    • hemashankar
    • December 14th, 2011

    how database connectivity in c# using sql

  1. This is a superb guide, thanks so much for posting both the instructions and the source code. But I have one question: is there a way to modify the items list in the ComboBoxColumns so that each row has a different items list. I’ve been trying to get it to work, but it seems as if the databinding prevents adding my own list of items.

    • salmanhooshmand
    • April 21st, 2012

    Hi Rahim, Thanks for your guide.
    However, when I select an Item from combobox it needs to click another cell to accept changes in dataset. what can i do :(

    • salmanhooshmand
    • April 21st, 2012

    Hi Rahim, Thanks for our guide.
    However, whenever I select an Item in combobox it needs to click on another cell to accept chanfes in the dataset. how can I overcome this probllem.

    • sree
    • June 7th, 2012

    Hi Rahim,
    Thanks a lot it was so use full.

    • naghma
    • July 20th, 2012

    Thanks
    Rahim this article is really helpful

    • Murali
    • November 3rd, 2012

    Thank you sir, It is very Useful sir

  2. Assalaam’u Alaikum Mr. Khan,

    I am a beginner in windows application and I need a help.
    I found your blog helpful and I got stuck in one requirement of datagridview.Hope you would be able to help me on it…..

    My requirement are as follows :-

    In my DataGridView of a windows application there are multi columns out of which one is dropdownlist from which I’ve to select a value and after selecting a value its subsequent data must be displayed in the same row i.e in the textbox.Also user can edit the data available in the textbox.And, dynamically the next row must be created for the same purpose.
    I am getting the values in dropdown list of first row and dynamically next row is also created but not getting the data filled in the textboxes, neither I’m getting values for the next row in the dropdown list, rather I’m getting an exception of Input string not in correct format.

    Please have a look at the code and let me know where am I going wrong.

    private void comboBox_SelectedIndexChanged(object sender, EventArgs e)

    {

    DataGridViewComboBoxColumn dgvComboBox;

    DataGridViewTextBoxColumn dgTxtBox;

    dgvc = (DataGridViewComboBoxColumn)dataGridInvoice.Columns["dgvProductCode"];

    int indexRow = dgvc.Index;

    dgTxtBox = (DataGridViewTextBoxColumn)dataGridInvoice.Columns["dgvProductName"];

    dgTxtBox = (DataGridViewTextBoxColumn)dataGridInvoice.Columns["dgvPriceColumn"];

    dgTxtBox = (DataGridViewTextBoxColumn)dataGridInvoice.Columns["dgvQuantityColumn"];

    //dgvc = (DataGridViewTextBoxColumn)dataGridInvoice.Columns["dgvTotalColumn"];

    string strText = dgvc.Selected.ToString();

    string strText1 = dgvc.ValueMember.ToString();

    string SelectedText = Convert.ToString((dataGridInvoice.Rows[indexRow].Cells["dgvProductCode"] as DataGridViewComboBoxCell).FormattedValue.ToString());

    int SelectedVal = Convert.ToInt32(dataGridInvoice.Rows[indexRow].Cells["dgvProductCode"].Value); //Format Exception

    string SelectedText1 = Convert.ToString((dataGridInvoice.Rows[indexRow].Cells["dgvProductCode"] as DataGridViewComboBoxCell).FormattedValue.ToString());

    int SelectedVal1 = Convert.ToInt32(dataGridInvoice.Rows[indexRow].Cells["dgvProductCode"].Value);

    ///

    ///Summary

    ///get the id from strText1 and pass it to the procedure along with command type ‘Id’ to fetch data of name and price of product

    DataTable dt_ProductCategory = b.BindInvoiceDataGridView(strText1, “Id”);

    DataGridViewTextBoxColumn dgTxtProductName = (DataGridViewTextBoxColumn)dataGridInvoice.Columns["dgvProductName"];

    //dgTxtProductName.DataSource = dt_ProductCategory

    }

    public DataTable BindInvoiceDataGridView(string id,string commandtype)

    {

    con.Open();

    cmd = new SqlCommand(“sp_InvoiceDataGridViewDisplay”,con);

    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue(“@prodId”, id);

    cmd.Parameters.AddWithValue(“@commandType”, commandtype);

    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);

    DataTable dtInvoiceDataGridViewDisplay = new DataTable();

    sqlDataAdapter.Fill(dsInvoiceDataGridViewDisplay);

    con.Close();

    return dtInvoiceDataGridViewDisplay;

    }

    public void BindingMethod()
    {
    DataTable dt1 = b.BindInvoiceDataGridView(“”, “All”);
    DataGridViewComboBoxColumn cbxColumn = dataGridInvoice.Columns["dgvProductCode"] as DataGridViewComboBoxColumn;
    cbxColumn.DataSource = dt1;
    cbxColumn.DisplayMember = “code”;
    cbxColumn.ValueMember = “prod_id”;
    }

    • afi
    • June 20th, 2013

    I have database tables in datagridview and delete button and I can delelte from all tables but one table can not delete how to do that ?

    • afi
    • June 20th, 2013

    Hi Just to clarify my last post I want one table from database to disable from delete button.

    • toby
    • October 14th, 2013
  1. January 3rd, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 74 other followers

%d bloggers like this: