C# DataGridView ComboBox Binding Issues - c#

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!

Related

Dynamically populating a ComboBox Column in a DataGridView

I have a DataGridView (DGV) which is populated using a datatable populated by a Stored Procedure. (All DB calls are correctly returning the requisite data). I then add a combobox column to the DGV which should provide a selection of batchcodes based on the stock code of that row. (Another Stored Procedure Call passing in the StockCode) However, all combo box's on every row are populating with the combined batchcodes for all the rows. In this example I have tried creating an array of datatables to dynamically assign to the DGV.Row but it's the same result. I kind of understand why it isn't working but I don't know how to rectify it. (I am assuming that since I am not specifically defining the cell index of the current combobox and assigning it's datasource to a datatable from the array - it is just overwriting it?? Any help would be greatly appreciated.
// fill the adapter with the executed cmd
adapter.Fill(dt);
//populate the gridview with the datatable
dgv_BOM.DataSource = dt;
dgv_BOM.AutoSize = true;
dgv_BOM.AutoResizeColumns();
dgv_BOM.Columns["StockCode"].DisplayIndex = 0;
dgv_BOM.Columns["Description"].DisplayIndex = 1;
dgv_BOM.RowHeadersVisible = false;
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "Select Batch Code";
cmb.Name = "cmb";
cmb.Width = 150;
dgv_BOM.Columns.Add(cmb);
DataTable[] dtArray = new DataTable[dgv_BOM.Rows.Count];
int count = 0;
foreach (DataGridViewRow row in dgv_BOM.Rows)
{
if (row.IsNewRow) continue;
stckcd = row.Cells["StockCode"].Value.ToString();
dtArray[count] = SP_RMBatchCodes(stckcd); //returns a datatable object
cmb.DataSource = dtArray[cnt];
cmb.DisplayMember = "BatchNo";
count++;
}
this.dgv_BOM.Columns["Traceable"].Visible = false;

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

ComboBox DataBinding C# WinForms

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

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 ?

How to display a column of sites links in a winform Datagridview which datasource is a Datatable containing data from DB

I have a datagridview in a winform that displays the content of a datatable which holds data recieved from my DB.
One column contains the urls of different sites.
I'd like to turn all the site urls into links e.g:
from : htttp://stackoverflow.com
to : http://stackoverflow.com
I think I found what I need in
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewlinkcolumn.aspx
but have no idea how to implement it in my code.
Thanks
Asaf
private void loadGRD()
{
string qry = "";
qry = "Select top 10000 companyName,webSite from jobDB.dbo.companiesAll ";
frmMainJobSearch a = (frmMainJobSearch)mainParent;
DataTable dt = new DataTable();
dt =a.connDB.userQuery(qry); // getting a table with one column of the databases names
grdHashamaLst.DataSource = dt;
}
Where you're defining your columns, you need something like this:
DataGridViewLinkColumn links = new DataGridViewLinkColumn();
links.UseColumnTextForLinkValue = true;
links.HeaderText = "Links"; //put the header text you want here
links.DataPropertyName = "webSite"; //This is from your query
links.ActiveLinkColor = Color.White;
links.LinkBehavior = LinkBehavior.SystemDefault;
links.LinkColor = Color.Blue;
links.TrackVisitedState = true;
links.VisitedLinkColor = Color.YellowGreen;
grdHashamaLst.Columns.Add(links);

Categories