I want to insert a combobox for each row in datagrid, but when I tried to send a combobox for specific cell it doesn't work
for (int i = 0; i < dtRecord.Rows.Count; i++)
{
int idRecord = Convert.ToInt32(dtRecord.Rows[i]["idRecord"].ToString());
DataTable dtDetalleRecordPorId = new DataTable();
dtDetalleRecordPorId = cnEvalua.CNListaDetalleRecord(idRecord);
DataGridViewComboBoxCell cmb = new DataGridViewComboBoxCell
{
DataSource = dtDetalleRecordPorId,
ValueMember = dtDetalleRecordPorId.Columns["idDetalleRecord"].ToString(),
DisplayMember = dtDetalleRecordPorId.Columns["cValor"].ToString(),
ReadOnly = false
};
dtgRecord.Rows[i].Cells["cValor"] = cmb;
}
When I debug and check datasource value of datagrid is empty. How can I insert that combobox?
My datagrid take data from this part:
dtRecord = cnEvalua.CNListaRecord();
dtgRecord.DataSource = dtRecord;
When I check datasource of gridview the column cValor is empty but other columns have data.
You can try this,
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DataSource = dtDetalleRecordPorId;
cmb.ValueMember = dtDetalleRecordPorId.Columns["idDetalleRecord"].ToString();
cmb.DisplayMember = dtDetalleRecordPorId.Columns["cValor"].ToString();
cmb.ReadOnly = false;
dtgRecord.Columns.Add(cmb);
I am binding DataGridViewComboBoxColumn to DataTable, but the the cells of the column are not displaying the bound table.
any idea?
to test the DataTable, I bound it to a normal ComboBox and this shows the expected behavior.
private void populateDataGW()
{
int addressesCount = data.Length / 186;
TestingAdrress[] addressArray = new TestingAdrress[addressesCount];
addressArray = getArray();
DataGridViewRow dtRow = new DataGridViewRow();
dtTableCmbBx = getAllCustomers();
DataGridViewComboBoxColumn cmBxCol = new DataGridViewComboBoxColumn();
//Binding here is not working
cmBxCol.DataSource = dtTableCmbBx;
cmBxCol.ValueMember = "Customer_ID";
cmBxCol.DisplayMember = "Name";
dtGrViTestAddress.Columns.Add(cmBxCol);
//code for "normal" combobox
comboBox1.DataSource = dtTableCmbBx;
comboBox1.DisplayMember= "Name";
comboBox1.ValueMember = "Customer_ID";
DataGridViewButtonCell btnCell = new DataGridViewButtonCell();
btnCell.Value = "Hinzufügen";
for (int i=0; i< addressArray.Length;i++)
{
dtGrViTestAddress.Rows.Add();
dtGrViTestAddress.Rows[i].Cells[0].Value = addressArray[i].Name;
dtGrViTestAddress.Rows[i].Cells[1].Value = addressArray[i].Street;
dtGrViTestAddress.Rows[i].Cells[2].Value = addressArray[i].PostalCode;
dtGrViTestAddress.Rows[i].Cells[3].Value = addressArray[i].City;
dtGrViTestAddress.Rows[i].Cells[5] = btnCell;
}
}
Here is a screenshot:
i found the problem. i wanted the datagridview to be readOnly, so thats why the combobox didnt show the items in it, now i changed this property, and i set it for each column separated, and let the comboboxcolumn to be readOnly=false
Method 1: Use Linq
var details = (from x in db.Details
orderby x.Datetime descending
where x.RaisedBy == "xyz"
select x).ToList();
comboBox1.ValueMember ="id";
comboBox1.DataSource = details;
comboBox2.ValueMember ="Name";
comboBox2.DataSource = details;
comboBox3.ValueMember ="Street";
comboBox3.DataSource = details;
comboBox4.ValueMember ="PostalCode";
comboBox4.DataSource = details;
Method :2
var combocolumnA = new DataGridViewComboBoxColumn();
combocolumnA.HeaderText = "ID"; // grid header name
combocolumnA.ValueMember = "id";// database Column name
combocolumnA.DataSource = details;
GV.Columns.Add(combocolumnA);
combocolumnA.Width = 100;
var combocolumnB = new DataGridViewComboBoxColumn();
combocolumnB.HeaderText = "Name";
combocolumnB.ValueMember = "Name";
combocolumnB.DataSource = details;
GV.Columns.Add(combocolumnB);
combocolumnB.Width = 150;
Edit:
Just to tell you one more thing... If you want the data in grid view suppose when you select name from combo box then data automatically change all fields of gridview according to database ?
I have to insert "Select" at top after combobox is bound from dataset.i tried this but it isn't working.Throws error "dataset doesn't have any definition for cast".I think i am not using it properly.Commented code is the part i tried but not working.
cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
// cmbCategory.Items.Add("Select");
// cmbCategory.SelectedText = "Select";
// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>());
You have to Insert to the object you are databinding to rather than to the combobox. You can't insert directly into the combobox.
You can use this:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("CategoryName");
DataRow dr = dt.NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 0;
dt.Rows.InsertAt(dr, 0);
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
cmbCategory.DataSource = dt;
cmbCategory.SelectedIndex = 0;
This is very straight forward example.
You cannot add items to a ComboBox after binding it to a data source. To add or remove items from a ComboBox with a bound data source, you have to do it through data source itself.
You can insert a DataRow into your table and it will be automatically added to your ComboBox. Try the following:
DataRow dr = dsCat.Tables[0].NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 123;// Some ID
dsCat.Tables[0].Rows.Add(dr);
// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>());
You might be able to do this, but your syntax is wrong somehow.
Maybe you can split it up until you figure it out and then compress it back into in-line functions.
List <object> catData = new List <object> { "Select" };
DataSet catByType = this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType);
foreach(DataRow oRow in catByType.Tables[0].Rows)
{ catData.Add(oRow.ItemArray[0]); }
But for this to work you need to consolidate your understanding of the data coming back from the GetCategoriesByType function. Will the objects be text like "Select"?.
You can use dsCat.Rows.Add method.
dsCat.Rows.Add(0, "Other"); // this will add row
cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
if add row to DataTable
DataRow row = datatable1.NewRow();
row["column2"]="column2";
row["column6"]="column6";
datatable1.Rows.Add(row);
How about DataGridView??
You can do:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
yourDataGridView.Rows.Add(row);
or:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);
Another way:
this.dataGridView1.Rows.Add("five", "six", "seven","eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");
From: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx
Like this:
var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....
Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...
Here's how you do it.
// Create a new row first as it will include the columns you've created at design-time.
int rowId = dataGridView1.Rows.Add();
// Grab the new row!
DataGridViewRow row = dataGridView1.Rows[rowId];
// Add the data
row.Cells["Column1"].Value = "Value1";
row.Cells["Column2"].Value = "Value2";
// And that's it! Quick and painless... :o)
Like this:
dataGridView1.Columns[0].Name = "column2";
dataGridView1.Columns[1].Name = "column6";
string[] row1 = new string[] { "column2 value", "column6 value" };
dataGridView1.Rows.Add(row1);
Or you need to set there values individually use the propery .Rows(), like this:
dataGridView1.Rows[1].Cells[0].Value = "cell value";
Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).
Create a clone row from RowTemplate is safer imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);
This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);
row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";
myDataGridView.Rows.Add(row);
According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".
If the grid is bound against a DataSet / table its better to use a BindingSource like
var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;
//Add data to dataTable and then call
bindingSource.ResetBindings(false)
here is another way to do such
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Age";
dataGridView1.Columns[2].Name = "City";
dataGridView1.Rows.Add("kathir", "25", "salem");
dataGridView1.Rows.Add("vino", "24", "attur");
dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
dataGridView1.Rows.Add("arun", "27", "chennai");
}
If you need to manipulate anything aside from the Cell Value string such as adding a Tag, try this:
DataGridViewRow newRow = (DataGridViewRow)mappingDataGridView.RowTemplate.Clone();
newRow.CreateCells(mappingDataGridView);
newRow.Cells[0].Value = mapping.Key;
newRow.Cells[1].Value = ((BusinessObject)mapping.Value).Name;
newRow.Cells[1].Tag = mapping.Value;
mappingDataGridView.Rows.Add(newRow);
If you are binding a List
List<Student> student = new List<Student>();
dataGridView1.DataSource = student.ToList();
student .Add(new Student());
//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;
If you are binding DataTable
DataTable table = new DataTable();
DataRow newRow = table.NewRow();
// Add the row to the rows collection.
table.Rows.Add(newRow);
yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value
you can also create a new row and then add it to the DataGridView like this:
DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);
If anyone wanted to Add DataTable as a source of gridview then--
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1"));
dt.Columns.Add(new DataColumn("column2"));
DataRow dr = dt.NewRow();
dr[0] = "column1 Value";
dr[1] = "column2 Value";
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
An example of copy row from dataGridView and added a new row in The same dataGridView:
DataTable Dt = new DataTable();
Dt.Columns.Add("Column1");
Dt.Columns.Add("Column2");
DataRow dr = Dt.NewRow();
DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
dr[0] = dgvR.Cells[0].Value;
dr[1] = dgvR.Cells[1].Value;
Dt.Rows.Add(dR);
dataGridView1.DataSource = Dt;
Consider a Windows Application and using Button Click Event put this code in it.
dataGridView1.Rows
.Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });
//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));
//List assigned to DataGridView
dgList.DataSource = item;
//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";
//add row by cell
dataGridView1.Rows[1].Cells[0].Value = "cell value";
If you´ve already defined a DataSource, You can get the DataGridView´s DataSource and cast it as a Datatable.
Then add a new DataRow and set the Fields Values.
Add the new row to the DataTable and Accept the changes.
In C# it would be something like this..
DataTable dataTable = (DataTable)dataGridView.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd["Field1"] = "Value1";
drToAdd["Field2"] = "Value2";
dataTable.Rows.Add(drToAdd);
dataTable.AcceptChanges();
I think the cleanest way to do is invoking the DataGridView and using a lambda expression. Simple one liner while also keeping the code thread safe:
MyDataGridView.Invoke((MethodInvoker)(() => MyDataGridView.Rows.Add(param1, param2, paramX)));
I have found this useful more than once when the DataGrid is bound to a table.
DataTable dt = (DataTable)dgvData.DataSource;
DataRow row = dt.NewRow();
foreach (var something in something)
{
row["ColumnName"] = something ;
}
dt.Rows.Add(row);
dgvData.DataSource = dt;
string[] splited = t.Split('>');
int index = dgv_customers.Rows.Add(new DataGridViewRow());
dgv_customers.Rows[index].Cells["cust_id"].Value=splited.WhichIsType("id;");
But be aware, WhichIsType is the extension method I created.
I am trying to create a gridview with a string column, a checkbox column, and a dropdownlist/combobox column. The first two are finished (all code behind), just need help with the last one.
DataTable dt = new DataTable("tblAir");
dt.Columns.Add("Flight Details", typeof(string));
dt.Columns.Add("Prefered Seating", typeof(bool));
//doesn't work
dt.Columns.Add("Add Remark", typeof(ComboBox));
The data for the combobox is being supplied on load as we cannot work with a database.
Peter Bromberg has a detailed article on creating a Winforms gridview with comboboxes:
http://www.eggheadcafe.com/articles/20060202.asp
DataAccessLayer dal = new DataAccessLayer();
DataTable movies = dal.GetMovies();
gvMovies.DataSource = movies;
gvMovies.AllowUserToAddRows = false;
gvMovies.AllowUserToDeleteRows = false;
//Create the new combobox column and set it's DataSource to a DataTable
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = dal.GetMovieTypes(); ;
col.ValueMember = "MovieTypeID";
col.DisplayMember = "MovieType";
col.DataPropertyName = "MovieTypeID";
//Add your new combobox column to the gridview
gvMovies.Columns.Add(col);