I found a way to add a combobox to DataGridview (Winform) cell, but I have not found an event like ItemDataBound of DataGridView to set a value to comboBox. And do not know how to set a selected value of a comboBox to DataItem property of a current row (of a DataGridView) :(
Please give me some clues to do this task
Thanks you so much
You can use below method to add data to a combobox in gridview. If you dont have a list you can add items to the combobox as:
cmbdgv.Items.Add("Test");
private void bindDataToDataGridViewCombo() {
DataGridViewComboBoxColumn cmbdgv = new DataGridViewComboBoxColumn();
List<String> itemCodeList = new List<String>();
cmbdgv.DataSource = itemCodeList;
cmbdgv.HeaderText = "Test";
cmbdgv.Name = "Test";
cmbdgv.Width = 270;
cmbdgv.Columns.Add(dgvCmbForums);
cmbdgv.Columns["Test"].DisplayIndex = 0;
}
After adding if you want to capture the combobox selection change you can use below event in the datagridview.
ComboBox cbm;
DataGridViewCell currentCell;
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
cbm = (ComboBox)e.Control;
if (cbm != null)
{
cbm.SelectedIndexChanged += new EventHandler(cbm_SelectedIndexChanged);
}
currentCell = this.dataGridView1.CurrentCell;
}
}
void cbm_SelectedIndexChanged(object sender, EventArgs e)
{
this.BeginInvoke(new MethodInvoker(EndEdit));
}
void EndEdit()
{
if (cbm != null)
{
string SelectedItem=cbm.SelectedItem.ToString();
int i = dataGridView1.CurrentRow.Index;
dataGridView1.Rows[i].Cells["Test"].Value = SelectedItem;
}
}
If you are trying to set the value to a Combobox in a DataGridView, see if this answer will help.
To get the selected item of the Combobox (example):
comboBox.SelectedIndexChanged += new EventHandler(comboBox_ComboSelectionChanged);
private void comboBox_ComboSelectionChanged(object sender, EventArgs e)
{
if (myDGV.CurrentCell.ColumnIndex == 5)
{
int selectedIndex;
string selectedItem;
selectedIndex = ((ComboBox)sender).SelectedIndex; // handle an error here.
// get the selected item from the combobox
var combo = sender as ComboBox;
if (selectedIndex == -1)
{
MessageBox.Show("No value has been selected");
}
else
{
// note that SelectedItem may be null
selectedItem = combo.SelectedItem.ToString();
if (selectedItem != null)
{
// Your code
Related
I have a comboBox with SelectedItemChanged event. So I want to extract value of selected item like:
private void cboCustomerType_SelectedIndexChanged(object sender, EventArgs e)
{
var db = new SQLConnMgr();
ComboBox cmb = (ComboBox)sender;
var comboSelectedValue = cmb.SelectedItem;
}
Problem is value I want is on cmb.SelectedItem.Row.ItemArray[1]
But I can't access to cmb.SelectedItem.Row. Why I can't do as simple as: cmb.SelectedItem.Row.ItemArray[1]? Regards
Your selected item type is DataRowView so you need to cast SelectedItem to that:
private void cboCustomerType_SelectedIndexChanged(object sender, EventArgs e)
{
// A combobox with nothing selected will have a SelectedIndex of -1
if (cboCustomerType.SelectedIndex > -1)
{
// Cast SelectedItem to DataRowView
DataRowView item = cboCustomerType.SelectedItem as DataRowView;
if (item != null)
{
// Access the data in column 1 of the selected row
string value = item[1].ToString();
}
}
}
I believe you are binding combobox with DataSet. So you can do this:
DataRow dataRow = dataSet.Select(string.Format("FieldName = '{0}'", ComboBox.SelectedValue.ToString()))[0];
if (ComboxBox.SelectedValue != null)
{
// can use fields like
String text = dataRow[“fieldName”].ToString();
}
else
{ //something wrong
}
}
Instead of
ComboBox cmb = (ComboBox)sender;
write
ComboBox cmb = sender as ComboBox;
This way it worked for me.
I have a datagridview binded to a BindingList and inside this list I have comboboxes binded to a list which is a property of my BindingList, for understanding better:
ListA ---> binded to datagridview
ListA.ListB ---> binded to comboboxes
When I open the form I can corectly set my comboboxes showing the values inside the ListB, but when I add a new item I get an error (value is not valid), here is the code:
private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
((DataGridViewComboBoxColumn)dataGridView.Columns["Names"]).DisplayIndex = 4;
for (int i = 0; i < People.Count; i++)
{
var cell = (DataGridViewComboBoxCell)dataGridView.Rows[i].Cells["Names"];
cell.DataSource = People[i].Names;
cell.Value = People[i].Names[0];
}
}
The code above works great, the problem happens here:
private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (dataGridView.CurrentCell.ColumnIndex != dataGridView.Columns["Names"].Index)
return;
var cell = (DataGridViewComboBoxCell)dataGridViewICAO.CurrentCell;
if (cell.EditedFormattedValue.ToString().Equals(String.Empty)) return;
var regex = new Regex("[a-zA-Z]");
if (!regex.IsMatch(cell.EditedFormattedValue.ToString()))
e.Cancel = true;
else
{
People[cell.RowIndex].Names.Add(cell.EditedFormattedValue.ToString());
cell.Value = People[cell.RowIndex].Names.Last();
People[cell.RowIndex].Names = cell.Value.ToString();
}
}
on the row code cell.Value = People[cell.RowIndex].Names.Last(); I get the exception... Thanks to all!
This is how I set the combobox:
private void AddComboBox()
{
var comboNames = new DataGridViewComboBoxColumn { Name = "cmbNames", HeaderText = "Names" };
dataGridView.Columns.Add(comboNames);
}
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView.CurrentCell.ColumnIndex == dataGridView.Columns["cmbNames"].Index)
{
var combo = e.Control as ComboBox;
if (combo == null)
return;
combo.DropDownStyle = ComboBoxStyle.DropDown;
}
}
I have a datagridview which contain a Combobox Column i want when i select a add value from the combobox it shows a new form. i tried this code but it doesn't work:
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
switch (dataGridView2.Columns[e.ColumnIndex].Name)
{
case "CategorieDataGridViewTextBoxColumn":
if (dataGridView2.Rows[e.RowIndex].Cells["CategorieDataGridViewTextBoxColumn"].Value.ToString() == "Add")
{
Categorie cat = new Categorie();
cat.Show();
}
break;
}
}
So how can i do it??
You should handle the event when a value is changed in a ComboBox in a DataGridView cell. try this code which will fire the event of the selection in the comboBox in the dataGridView:
public Form1()
{
InitializeComponent();
DataGridViewComboBoxColumn cmbcolumn = new DataGridViewComboBoxColumn();
dataGridView2.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView2_EditingControlShowing);
}
private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
string item = cb.Text;
if (item == "Add")
{
Categorie cat = new Categorie();
cat.Show();
}
}
Hi i have a datagrid in window form called "dataGridView1" and i have combobox in the dataGridView1; i am displaying the data in combobox from database and all data loads in that combobox when window loads. i have function LoadModels for that. there is one column ModelName which i want to display and in valuemember there will be MedelID, so i want when user select any model from combobox then it give me id of that model called "ModelID".
public frmBikeOrder()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
FormBorderStyle = FormBorderStyle.FixedSingle;
ControlBox = false;
LoadModels();
}
private void LoadModels()
{
RST_DBDataContext conn = new RST_DBDataContext();
List<TblBikeModel> AllModels = (from s in conn.TblBikeModels
select s).ToList();
Column2.DataSource = AllModels;
Column2.DisplayMember = "ModelName";
Column2.ValueMember = "ModelID";
}
i have a function when value changes, i want the value in messagebox after combobox value change
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
ComboBox cmb = ComboBox();
MessageBox.Show(cmb.SelectedValue.ToString());
}
}
use this
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
bool val = (bool)dataGridView1.SelectedCells[0].Value;
MessageBox.Show(val.ToString());
}
}
you get the selected cell using dataGridView1.SelectedCells[0] and it's value(is checked) with the value Property.
you can also use the DataGridViewCellEventArgs and do:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
bool val = (bool)dataGridView1[e.ColumnIndex, e.RowIndex].Value;
MessageBox.Show(val.ToString());
}
}
Set the property of combobox as:
ModelComboBox.SelectedValuePath = "ModelID";
ModelComboBox.DisplayMemberPath = "ModelName";
Then ModelComboBox.SelectedValue will be ModelID.
I am trying to enter values in a datagridview Combobox. but it does not Allows. What to do?
private void GridStockItemEntry_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewRow row = GridStockItemEntry.CurrentRow;
DataGridViewCell cell = GridStockItemEntry.CurrentCell;
if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
{
if (cell == row.Cells["ItemName"] && Convert.ToString(row.Cells["Type"].Value) == "Raw Material")
{
DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl;
cbo.DropDownStyle = ComboBoxStyle.DropDown;
cbo.Validating += new CancelEventHandler(cbo_Validating);
}
}
}
void cbo_Validating(object sender, CancelEventArgs e)
{
DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl;
DataGridView grid = cbo.EditingControlDataGridView;
object value = cbo.Text;
// Add value to list if not there
if (cbo.Items.IndexOf(value) == -1)
{
DataGridViewComboBoxCell cboCol = (DataGridViewComboBoxCell)grid.CurrentCell;
// Must add to both the current combobox as well as the template, to avoid duplicate entries...
cbo.Items.Add(value);
cboCol.Items.Add(value);
grid.CurrentCell.Value = value;
}
}
Maybe, this example is better readable:
private void datagridview_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
DataGridView dgv = (DataGridView)sender;
if(dgv.CurrentCell.ColumnIndex==dgv.Columns["ColumnName"].Index) {
ComboBox cbx = (ComboBox)e.Control;
cbx.DropDownStyle = ComboBoxStyle.DropDown;
cbx.AutoCompleteSource = AutoCompleteSource.ListItems;
cbx.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
}
}
Make sure that EditMode property of the DataGridView is set to EditOnKeystrokeOrF2
Also, verify that ReadOnly property is set to False.