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
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;
}
hi sir i have problem for developing a windows form how should i retrive data from sql in the griedviewcomboboxcolumn and after selecting a value from griedviewcomboboxcolumn it should given its value in griedviewtextboxcolumn and how should inserting all that value in sql database
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.
hi dear
thank you.
you are welcome
many many thanks this code very great,hope so you bring all things you want.
so thanks
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
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…
how database connectivity in c# using sql
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.
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 :(
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.
Hi Rahim,
Thanks a lot it was so use full.
Thanks
Rahim this article is really helpful
Thank you sir, It is very Useful sir
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”;
}
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 ?
Hi Just to clarify my last post I want one table from database to disable from delete button.
No help at all.
Create custom ComboBox column with C# DataGridView
A complete …C# Datagridview Tutorial
croby
Assalomu aleykum, Mr. Khan.
This artile very useful. But I’ve found some problems with saving db. New added information doesn’t save in db after closing application.
The above logic helped me a great thing in my development of project.
Thanks Rahim you saved my time !!!! I was really wasting a lot of time on this but your blog saved me. Thank you from my heart.
Hi, if you have one BindingList e.g. :
BindingList XYZ = new BindingList();
And an Item of BindingList has data of a TextBox-Cell and a ComboBox-Cell of one row. If the user now changing data of the
ComboBox he want to display it immediately on the screen.
Can it be achieved with only one List whitch is directly bind to
the datagridview:
DataSource_of_the_datagridview = XYZ;
Could it happen if there is a change on the ComboBox, that
the underlying data of the BindingList and furthermore also
the displayed data of the datagridview will be changed?
Thank you for help.
Thank you for the very useful and great post and sample project.
Thank you so much for your beautiful and easy demonostration.
hi
I need same code in visual studio C# not asp
Please help me
A Rahim Khan,
Thank you for the code.
I have an issue:
I have Fields like TextBoxes, Comboxes, DataGridView and Button,
Now, the Textboxes and Comboboxes accept values from users & on pressing the Button, the values from the textboxes automatically get added to DataGridView.
It’s easy to add values from Textboxes to DataGridView,
But, How do I add values form Comboboxes to DataGridViews?
Note: I have TextBox Columns & Combobox Columns in my DataGridView
Please help out.
About 2 days researching this topic, this is the first decent post I’ve found on it. Kudos Rahim.
I FOLLOW YOUR INSTRUCTIONS AND BECOME ABLE TO PUT COMBO BOX IN A DATAGRIDVIEW. BUT I AM FACING AN ISSUE, IF USER WANT TO DESELECT VALUE(NO VALUE OR REST) OF COMBO BOX, HOW IT WILL DO WITHOUT REMOVING THE THE GRID ROW..??
THANKS
Thank you, man!!!! Very good information. The best post!!!!