DataGridView - ComboBox # runtime - c#

I have a DataGridView where I set the DataSource to a collection of objects when the tab the DataGridView resides is selected.
After the datasource is set I'd like to change the "County" column to a DataGridViewComboBoxColumn with the state's counties as the items. Nothing I've seen works yet - it always gives an exception.
Is there a way to change the column type without deleting it?
Is there a way to have a combobox or other control appear when I click on a cell in that row without having to modify the column type?
======================== My Failing Code ========================
//ii is a for loop variable on the dataGridViewFields.Columns.Count
string colName = dataGridViewFields.Columns[ii].Name;
if (colName.Equals("County"))
{
string dpName = dataGridViewFields.Columns[ii].DataPropertyName;
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
//get current column characteristics.
column.ValueType = dataGridViewFields.Columns[ii].ValueType; ;
column.Name = dataGridViewFields.Columns[ii].Name;
column.HeaderText = dataGridViewFields.Columns[ii].HeaderText;
column.Width = dataGridViewFields.Columns[ii].Width;
//remove column from grid
dataGridViewFields.Columns.RemoveAt(ii);
//set column combobox characteristics
column.DropDownWidth = 160;
column.MaxDropDownItems = 10;
column.Items.AddRange(new string[] {"Dane", "Dodge", "Door"});
column.FlatStyle = FlatStyle.Flat;
DataGridViewCell cell = new DataGridViewComboBoxCell();
cell.Style.BackColor = Color.Wheat;
cell.ValueType = typeof(string);
cell.Value = "Door";
column.CellTemplate = cell;
//add to the grid.
dataGridViewFields.Columns.Insert(ii, column);
dataGridViewFields.Columns[ii].DataPropertyName = dpName;
//dataGridViewFields.EditMode = DataGridViewEditMode.EditProgrammatically;
}

I think you would be interested in the DisplayStyle of the ComboBox Column
Set DisplayStyle to Nothing. This will make the ComboBox appear only when you try to Edit the cell

Related

DatagridView with variable number of columns

I want to create a datagridview in C# (winform) with a variable number of columns. I have done this
dataGridView2 = _dm.CreateGrid();
where CreateGrid() is the following method:
public DataGridView CreateGrid()
{
DataGridView dtgr = new DataGridView();
using (DbEntities db = new DbEntities())
{
foreach (Resource r in db.Resources)
{
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.ValueType = typeof(string);
col.Name = r.Description;
col.HeaderText = r.Description;
col.DataPropertyName = r.Description;
dtgr.Columns.Add(col);
}
}
return dtgr;
}
Description is of type string. I don't see the datagridview in my winform. Where is the problem ?
I think DataGridViewTextBoxColumn is causing the problem. Try using DataGridViewColumn instead. Hope that helps.
You need add your DataGridView to controls of the Form
dataGridView2 = _dm.CreateGrid();
this.Controls.Add(dataGridView2);
Why you create columns manually. DataGridView will generate columns automatically based on the columns/fields of the datasource, if you set AutoGenerateColumns = true
From MSDN DataGridView.AutoGenerateColumns Property

how to add a combo box in a datagrid view for only one cell dynamically

I am reading an xml file using dataset and then i am creating a datagridview and assigning the table from dataset to datagridview.datasource dynamically.
The problem i am facing here is, i want to add a combobox for one cell in datagridview.
Below is my code :
datagridview1.AllowUserToAddRows = false;
datagridview1.AllowUserToDeleteRows = false;
datagridview1.RowHeadersVisible = false;
datagridview1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
datagridview1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
datagridview1.DataMember = "";
datagridview1.DataSource = my_dataTable;
datagridview1.Columns["first name"].ReadOnly = true;
datagridview1.Columns["Second name"].Visible = false;
datagridview1.Columns["place"].Visible = false;
datagridview1.Columns["address"].Visible = false;
string[] datasource = { "add1", "add2" };
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
combo.DataSource = datasource;
datagridview1.Rows[2].Cells[2] = combo;
It is giving me datagridviewcomboboxcell value is not valid error.If i give some value then it runs well but not able to see the combobox in datagridview.
You can use the DataSource to feed to Items, but using a simple string array will not work.
Instead you can convert the array to a List<string> :
string[] datasource = { "add1", "add2" };
DataGridViewComboBoxCell combo = new DataGridViewComboBoxCell();
combo.DataSource = datasource.ToList();
DGV.Rows[2].Cells[2] = combo;
To set a value you can use..
combo.Value = combo.Items[0];
..after having set the cell.
For better control, especially for having spearate Display- and ValueMembers you can switch to a Dictionary or use a List<someClass>..

c# how to set several combobox column in datagridview

I have been able to make one existing column combo box column in the datagridview, how do I do it for several columns? Also how do I add existing distinct records in the combobox items? The user will be able to either choose value from combobox item or write their own. So far my code is:
dgvLoadTable.DataSource = null;
var context = new CadAdminEntities();
var TableName = cboSelectTable.Text.ToString();
var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
var truncatedData = ((IQueryable<object>)rawData).Take(0);
var source = new BindingSource { DataSource = truncatedData };
dgvLoadTable.DataSource = source;
dgvLoadTable.ReadOnly = false;
dgvLoadTable.AllowUserToAddRows = true;
DataGridViewComboBoxCell dgvCol = new DataGridViewComboBoxCell();
for (int row= 0; row < dgvLoadTable.Rows.Count; row++)
{
for (int col = 0; col < dgvLoadTable.Columns.Count; col++)
{
if(col==2||col==4)
this.dgvLoadTable[col,row] = dgvCol;
//This part throws error, as there is only one combobox
}
}
dgvLoadTable.Refresh();
This is easy to fix:
this.dgvLoadTable[col, row] = new DataGridViewComboBoxCell();
will create a fresh ComboBoxCell for each case.
You can delete the line
DataGridViewComboBoxCell dgvCol = new DataGridViewComboBoxCell();
Note that since you have a Databound DGV and the Columns were probably created automatically, you should keep in mind, that often one needs to switch off that automatism and create all column manually before setting the DataSource..

How to set a DataGridView column to a DataGridViewComboBoxColumn?

Here is my code:
DataSet data = new DataSet();
data.ReadXml("data.xml");
DataGridView grid = new DataGridView();
var genreCboBoxItems = data.Tables[0].AsEnumerable().Select(genre => genre.Field<string>("genre")).Distinct().ToArray();
// TODO: Make is so the 'genre' column in grid is a combo box?
grid.DataSource = data.Tables[0];
grid.Dock = DockStyle.Fill;
this.Controls.Add(grid);
*edit: genreCboBoxItems
Try this: (not tested)
var column = new DataGridViewComboBoxColumn();
column.DataSource = data.Tables[0].AsEnumerable().
Select(genre => new { genre = genre.Field<string>("genre") }).Distinct();
column.DataPropertyName = "genre";
column.DisplayMember = "genre";
column.ValueMember = "genre";
grid.DataSource = data.Tables[0];
// Instead of the below line, You could use grid.Columns["genre"].Visible = false;
grid.Columns.Remove("genre");
grid.Columns.Add(column);
This might help you cast DataGridViewColumn to DataGridViewComboBox.
First create DataGridViewComboBoxColumn using designer with proper name. Then say you have a list of String list and other string values to bind to that datagridview then use this code:
Below code will bind a list to two DataGridViewTextBoxCell and a DataGridViewComboBoxCell. Note AllCriterias is a list with two string values and a list of string. DGVEligibilityCriteria is the grid name.
for (int i = 0; i < AllCriterias.Count; i++)
{
DataGridViewTextBoxCell Cmb1 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[0];
Cmb1.Value = AllCriterias[i].Name;
DataGridViewTextBoxCell Cmb2 = (DataGridViewTextBoxCell)DGVEligibilityCriteria.Rows[i].Cells[1];
Cmb2.Value = AllCriterias[i].Type;
DataGridViewComboBoxCell Cmb = (DataGridViewComboBoxCell)DGVEligibilityCriteria.Rows[i].Cells[2];
foreach (var filtervalue in AllCriterias[i].FilterValues)
{
Cmb.Items.Add(filtervalue);
}
}
Need to display the fist index as default by setting selectindex property.
Use this code : Here "filterValues" is the name of the DataGridViewComboBoxCell which u created in the datagridview designer.
foreach (DataGridViewRow row in DGVEligibilityCriteria.Rows)
{
row.Cells["filterValues"].Value = (row.Cells["filterValues"] as DataGridViewComboBoxCell).Items[0];
}

Hot to change specific column header color only in datagridview?

Uses: VS 2005, C#, DataGridView, WinForms;
I need to color the font/background of a particular column's Header portion. I see that it can only be done to the entire column list's header instead of a single column. Any help greatly appreciated.
First in your DataGridView you need to set EnableHeadersVisualStyles to false.
After you've done that you can set the individual header style on each column.
DataGridViewColumn dataGridViewColumn = dataGridView1.Columns[0];
dataGridViewColumn.HeaderCell.Style.BackColor = Color.Magenta;
dataGridViewColumn.HeaderCell.Style.ForeColor = Color.Yellow;
Do it in this way
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
{
col.Name = "ColumnName";
col.HeaderText = "HeaderName";
col.DefaultCellStyle.ForeColor = Color.White;
col.HeaderCell.Style.BackColor = Color.Red; //Column Header Color
this.dataGridView1.Columns.Add(col);
}
Create a method name called SetUpDataGridView
private void SetUpDataGridView()
{
dataGridView1.Columns[0].HeaderText = "Emp.Id";
dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Chartreuse;
dataGridView1.Columns[1].HeaderText = "Emp. Name";
dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Fuchsia;
}
Add the method in Form_Load.
You can add different color for every header

Categories

Resources