ComboBox DataBinding C# WinForms - c#

I have 2 Tables:
Diagnose: ID, Name
DiagnoseForPatients: PatientID, DiagnoseID.
I have A DateGridView with 2 ComboBoxes: First ComboBox needs to show the ID of the Diagnose, And the second one needs to show the name.
When I'm adding a new row to my DataGridView I'm Getting an Exception saying DiagnoseID Can't be null (although I chose ID On first ComboBox).
I'm using this code to add the ComboBox's to my DataGridView:
ClinicTableAdapters.DiagnoseTableAdapter daDiagnoses = new ClinicTableAdapters.DiagnoseTableAdapter();
Clinic.DiagnoseDataTable dtDiagnosesAdd = daDiagnoses.GetData();
DgDiagnosesAdd.AutoGenerateColumns = false;
col1.HeaderText = "ID";
col1.DataPropertyName = "ID";
col1.Name = "ID";
col1.ValueMember = "ID";
col1.DisplayMember = "ID";
col1.DataSource = dtDiagnosesAdd;
DgDiagnosesAdd.Columns.Add(col1);
col2.HeaderText = "Name";
col2.DataPropertyName = "Name";
col2.Name = "Name";
col2.ValueMember = "Name";
col2.DisplayMember = "Name";
col2.DataSource = dtDiagnosesAdd;
DgDiagnosesAdd.Columns.Add(col2);
I'm using the DataGridView For Adding Diagnoses For patient. The DataGridView Is binded to DiagnosesForPatients DataTable.
How can I bind the DiagnoseID?
ON WPF VB.NET I use:
cmb.SelectedValueBinding = New Binding("DiagnoseID")
How should I Write it on WinForms?

One column is enough for handling "Diagnose" information
DgDiagnosesAdd.AutoGenerateColumns = false;
col1.HeaderText = "Diagnose";
//Next line will bind DiagnoseForPatients.DiagnoseID to Diagnose.ID
col1.DataPropertyName = "DiagnoseID";
col1.Name = "DiagnosesDiagnoseID";
col1.ValueMember = "ID";
col1.DisplayMember = "Name"; //Name column will be used as display text
col1.DataSource = dtDiagnosesAdd;
DgDiagnosesAdd.Columns.Add(col1);
About Exception saying DiagnoseID Can't be null
Seems like DiagnoseID column's property AllowDbNull = false.
Set DataColumn.AllowDbNull = true
Or set DataColumn.DefaultValue = 1 or some other default value for column
If you haven't access to the DataTable's column, then you can set default values for new rows in the DataGridView1.DefaultValuesNeeded eventhandler
private void DataGridView1_DefaultValuesNeeded(Object sender, DataGridViewRowEventArgs e)
{
int comboBoxColumnIndex = 1;
int diagnoseIDDefaultValue = 1;
e.Row.Cells[ComboBoxColumnIndex].Value = diagnoseIDDefaultValue;
}

Related

How to Insert DataGridViewComboBoxCell in DataGridView?

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);

Binding DataGridViewComboBoxColumn to DataTable is not working

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 ?

DataGridViewComboBoxColumn set the selectedindex

hi i runtime bind the data into datagridview combobox. But how do i make it to auto display the first item? i do not able find the selectedindex from DataGridViewComboBoxColumn.
DataGridViewComboBoxColumn cbStudentCourse = (DataGridViewComboBoxColumn)dgStudentCourse.Columns["studentCourseStatus"];
cbStudentCourse.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
cbStudentCourse.DisplayIndex = 1;
-- Update ---
i saw someone doing this in solution 3
LInk
Are you sure i need such a long code to just have the first item selected??????
A DataGridViewComboBoxColumn has no SelectedIndex, and SelectedValue properties. However you can get the same behavior of SelectedValue by setting the Value property.
For instance on first index the value member has value 2 then you should set .Value = "2" to set the first index selected.
For example
myDataGridViewComboBoxColumn.Value = "20";
In your case
myDataGridViewComboBoxColumn.Value = CourseStudentStatus.EnumToBeSelected.ToString();
Here is more details about DataGridViewComboBoxColumn
the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well

how to set checkbox value false in datagridview one row

how to set checkbox value false in datagridview one row
private void dgvTodaysPlan_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvTodaysPlan.CurrentCell is System.Windows.Forms.DataGridViewCheckBoxCell)
{
dgvTodaysPlan.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
try this
// Add a new Column (ComboBox)
DataGridViewComboBoxColumn colForeign = new DataGridViewComboBoxColumn();
colForeign = MyDB.CreateComboBoxColumn("SELECT subjno,subject FROM subject", "ComboForeign", "subject", "subjno");
colForeign.HeaderText = "Subject";
colForeign.Width = 120;
colForeign.DisplayStyle = 0;
this.dataGridView2.Columns.Insert(3, colForeign)
Use DataPropertyName to get the selected key column as in :-
this.dataGridView2.Columns[3].DataPropertyName = "subjno";
It appears that this would be much easier in VisualStudio - maybe??
And here is the routine to Create the Combobox Column - very messy compared with Delphi :-
public DataGridViewComboBoxColumn CreateComboBoxColumn(string strSQLSelect, string strColName, string strDisplay, string strValue)
{
// Returns the DataGridViewComboBoxColumn to be inserted
DataGridViewComboBoxColumn colComboColumn = new DataGridViewComboBoxColumn();
DataTable dtbElements = new DataTable();
MySqlDataAdapter dbaElements = new MySqlDataAdapter(strSQLSelect, conn);
// Set some parameters for the ComboBoxColumn
colComboColumn.Name = strColName;
colComboColumn.DisplayMember = strDisplay;
colComboColumn.ValueMember = strValue;
// Add the Elements
dbaElements.Fill(dtbElements);
colComboColumn.DataSource = dtbElements;
// Return the column
return colComboColumn;
}
If the userAddedRow flag is set to true, unset the flag;
userAddedRow = false; and set id to 0, valid because autoincremented id's from server starting from 1 :-
dataGridView1["bookno", e.RowIndex].Value = 0;
You should convert it into a datagridviewcheckbox and set its value to false.

C# DataGridView ComboBox Binding Issues

I've got a C# program that I'm working on but I can't get the ComboBoxColumn to display as I want it to.
I have two tables. One Contains a list of price. (Columns: PriceID, PartID, Price, MinimumQuantity, CustomerID, ExpiryDate) The other table, a list of parts contains (Columns: PartID, PartNumber). What
I want to do is display the PartNumber in a ComboBoxColumn with the PartID as the value. But I want to corresponding part number selected automatically for each price row.
Does this make sense!?
What I am currently getting in each row is the prices, quantities and expiry dates and ComboBoxColumn with the parts list populating the combobox but no value selected.
Please can someone help me with this.
Please see the code below.
DbConnection dbConn = new DbConnection(getConnectionStr());
dbConn.execQuery("EXEC RBS_CustomerSpecificPriceListSelect " + customerID + ";", "CustomerPriceList");
dbConn.execQuery("EXEC RBS_PartsSelect;", "Parts");
DataTable dtCustomerPrices = dbConn.getDataTable("CustomerPriceList");
DataTable dtParts = dbConn.getDataTable("Parts");
dgvCustomerPrices.AutoGenerateColumns = false;
dgvCustomerPrices.DataSource = dtCustomerPrices;
dgvCustomerPrices.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
SetupDGVColumns(dtCustomerPrices, dtParts);
Then to generate the columns.
private void SetupDGVColumns(DataTable dtCustomerPrices, DataTable dtParts)
{
// Parts Dropdown
DataGridViewComboBoxColumn cboPartsColumn = new DataGridViewComboBoxColumn();
cboPartsColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
cboPartsColumn.DataSource = dtParts;
cboPartsColumn.HeaderText = "PartNumber";
cboPartsColumn.DisplayMember = "PartNumber";
cboPartsColumn.ValueMember = "PartID";
cboPartsColumn.DataPropertyName = "PartID";
cboPartsColumn.Width = 110;
cboPartsColumn.AutoComplete = true;
dgvCustomerPrices.Columns.Add(cboPartsColumn);
// MinimumQuantity Textbox
DataGridViewTextBoxColumn tbcMinimumQuantityColumn = new DataGridViewTextBoxColumn();
tbcMinimumQuantityColumn.DataPropertyName = "MinimumQuantity";
tbcMinimumQuantityColumn.HeaderText = "MinimumQuantity";
tbcMinimumQuantityColumn.ValueType = typeof(double);
tbcMinimumQuantityColumn.Width = 140;
tbcMinimumQuantityColumn.DefaultCellStyle.Format = "#####0.00";
dgvCustomerPrices.Columns.Add(tbcMinimumQuantityColumn);
// Price Textbox
DataGridViewTextBoxColumn tbcPriceColumn = new DataGridViewTextBoxColumn();
tbcPriceColumn.DataPropertyName = "Price";
tbcPriceColumn.HeaderText = "Price";
tbcPriceColumn.ValueType = typeof(double);
tbcPriceColumn.Width = 100;
tbcPriceColumn.DefaultCellStyle.Format = "#####0.00";
dgvCustomerPrices.Columns.Add(tbcPriceColumn);
// ExpiryDate Textbox
DataGridViewTextBoxColumn tbcExpiryDateColumn = new DataGridViewTextBoxColumn();
tbcExpiryDateColumn.DataPropertyName = "ExpiryDate";
tbcExpiryDateColumn.HeaderText = "ExpiryDate";
tbcExpiryDateColumn.ValueType = typeof(string);
tbcExpiryDateColumn.DefaultCellStyle.Format = "d";
dgvCustomerPrices.Columns.Add(tbcExpiryDateColumn);
}
Ok so this was complete idiocy on my part. The SQL query that was selecting the combo columns data did not have the corresponding row ID in the SELECT clause.
Thank you all for your help though! I feel silly!

Categories