Getting PK value from data grid view - c#

I have a data loaded from database into dataGridView, with effect looking like this:
(in final version I would prefer to hide the PatientID column)
What I'm trying to do, is return value of PatientID when user clicks ANYWHERE in the corresponding row (i.e. user clicks "Doe" and value returned is "2"). Could anyone give me a hint how to do this? I don't think there is valueMember property... I was trying Rowindex but that returns value of number of row counting from the top(D'uh?!)
Also, is there a way for user to highlight whole row when clicking on the single cell?
EDIT: Oh God, I've spent few hours late at night to find this, In the morning I gave up and posted here... just to find answer 5 minutes later:
string test = dataGridView1.Rows[e.RowIndex].Cells["PatientID"].FormattedValue.ToString();
Still, that leaves my second question about highlighting whole row.

If the datagridview is bound to some data source (DataView), you can use DataBoundItem property, for example
DGV.CurrentRow.DataBoundItem["PatientID"]
or
DGV.SelectedRows[0].DataBoundItem["PatientID"]
or
DGVUnderlyingBindingSource.Current["PatientID"]
If the DataGridView is bound to a strongly typed data source (e.g. BindingList) then you can use the above like this:
((PatientType)DGV.CurrentRow.DataBoundItem).PatientID
or
((PatientType)DGV.SelectedRows[0].DataBoundItem).PatientID
or
((PatientType)PatientTypeBindingSource.Current).PatientID
About the second part of the question, set the DataGridView's SelectionMode property to FullRowSelect
EDIT
You can't use the solution from your edit if you hide that column. In order to access the value by using .Cells[idx].FormattedValue that value must be visible. But you can use this one even if you hide the column.

For the second question, set selection mode to FullRowSelect and the complete row will be highlighted when the user clicks on it. You can set this attribute in the designer or code:
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

Related

How do I connect a binding to a (Winform) ComboBox control to get/set the selection in the control from the binding source?

I have plumbed the deeps of my google-fu to find an answer.
First, I am not simply asking how to bind a combobox to a datasource. It's a bit more than that unless I'm having a serious understanding gap.
On my Winform, I have a DataGridview on the left and on the right I have a panel with values from the selected row on the left. One of those controls on the right is the ComboBox I'm having trouble with. I have my bindingsource and dataview set up and the other controls on the right are working splendidly, except the ComboBox control.
The user, interacting with this ComboBox, should see values such as "Item ABC" and "Item EFG" and the value related to them might be 1234 and 5678. If this was a fully unbound control I'd put an object array of items in. Once I get it working, I'd load that from a different source.
But when I try to DataBindings.Add("??", dataview, "dataviewfield", ...) I can't get the proper value for "??". Runtime debug shows that "SelectedItem.Value" would be the right option, but I get "not found" type exception when I use that. I've tried "SelectedValue" as well, but that didn't work (debug show's it's null & throws no nulls allowed exception).
How can I get that value placed directly into the DataView via the Binding?
Setting the .DataSource simply loses the items and doesn't help at all.
How does one do this? Short of making the ComboBox unbound totally, setting the selectedindex directly and capturing the value when the selected index changes changes - Just seems so clunky to have to do that.
-old programmer
Further Notes: I edited to clarify the placement of the ComboBox.
I have made progress (naturally, only after asking a question does a new avenue pop into my head). I got to thinking I might need a custom binding adapter so started googling that. I found some samples doing what I want.
The foremost problem was I was not using assigning a datasource on the ComboBox, I was simply adding items. When I created a two column dataset and a few rows (could have been anything I suppose) and set that and the two field names as the ComboBox's displaymember and valuemember did the SelectedValue start showing a value (instead of null all the time).
I think that was the problem. The remaining issue is getting the left hand side to re-display/refresh after the change.
When loading the datasource for the DataGridView and the bindingsource, try making them share the same list:
BindingSource1.Datasource = dataset
DataGridView.Datasource = BindingSource1
This should mean that any changes to the data in the bindingsource will also update the DataGridView.
To edit the selected object then just handle the SelectionChanged event and set the BindingSource1.Position to the index of the selected object in the Datasource.

Turning individual cells of DataGridView into Combobox

Environment: Web Development in Visual Studio
Language: ASP.NET
I'm afraid I already know the answer, but it can't hurt to ask. I have an application that gets data from SAP and can return specific results or a list of possible results for each row of a DataGridView. So the user might enter "abcd" and get "1234" as a result or he might get "1234 or 2345 or 3456" as a result. For each row I would like to have each column where multiple results were returned as a combobox. The rest should stay fixed though, since having the table littered with comboboxes that only have one result would be annoying.
Is there any trick to do this? I know you can "convert" an entire column into a column of comboboxes using DataGridViewComboBoxColumn like in this blog:
http://mytactics.blogspot.de/2014/01/convert-datagridview-column-to-combo-box.html
.Is there any way to have a combobox only for specific cells though? I know I could put a combobox next to each row of the table and let the user choose from that one or I could have a combox in every single row and maybe lock the ones with only one result. I'm not happy about either of those solutions though.
You can try and add a ComboBox to yourDataGridViewCell.Controls and make the label.Visible = false; or remove it. It would be something like:
yourDataGridViewCell.Controls.Clear();
yourDataGridViewCell.Controls.Add(new ComboBox());
yourDataGridViewCell.Controls[0].DataSource = yourList;
//set the value member etc.

How to get the TEXT of Datagridview Combobox selected item?

How to get the Combobox selected item text which is inside a DataGridView?
I have tried using the below code:
dataGridView1.Rows[1].Cells[1].Value.ToString()
But, this gives the value associated with this cell, not the Combobox selected item text.
I also tried this:
DataGridViewComboBoxCell cell = dataGridView1[1,1] as DataGridViewComboBoxCell;
string value = cell.Value.ToString();
But, this also didn't help.
I would appreciate your help. Thanks in advance!
EDIT:
Let's say, we have a Combobox with text as No and Yes and the values as 0 and 1 respectively. What I want to get here's the text Yes or No, when the Combobox is changed. But what I am getting is the values 0/1 using the above codes. Hope that makes things clear.
UPDATE:
Ok, so I have been working on this issue and after lots of efforts and with help from my fellow members, I have been able to resolve the issue and get the required solution:
Here's the solution:
string SelectedText = Convert.ToString(dataGridView1.Rows[0].Cells[1].FormattedValue.ToString());
To get selected value and selected text of Combobox in DataGridView try following Code
string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());
int SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);
I managed to pull that string value out of the cell this way:
DataGridViewComboBoxCell dgvcmbcell = dataGridView1[1, 0] as DataGridViewComboBoxCell;
String text = dgvcmbcell.EditedFormattedValue.ToString();
Easiest way to figure this out is use the debugger and look into the dgvcmdcell object. In this you will find the expandable node "base". Expand it and just look through it and you will find whatever information you need.
Also try this:
DataGridView.CurrentRow.Cells(Column.name).EditedFormattedValue.ToString()
EditedFormattedValue object gives the current, formatted value of the cell in DataGridView, regardless of the cell is edited or in edit mode. It's more convenient to capture the ComboBox selection or any value of cell in DataGridView.
To access the currently selected text in the datagridview, you need a reference to the CurrencyManager of the Combobox column. The CurrencyManager has nothing to do with money but instead manages the binding between the the column and it's datasource. The CurrencyManager can tell you what the current selection of the combobox is.
Teh codes:
CurrencyManager cm = (CurrencyManager)DataGridView1.BindingContext[((System.Windows.Forms.DataGridViewComboBoxColumn)DataGridView1.Columns[0]).DataSource];
Note: it is not necessary to cast the column to a combobox, i just did that to show you what column I was passing in. I used index 0 but use whatever index is the actual index of your combobox column.
Now using the currency manager you can access the current selection of the datagrid for that column (because that was the column you passed in).
cm.Current; //returns the current selection whatever that is
So in my case the datasource of the combobox column was a class called Choice, choice looks like this:
public class Choice
{
public string Text
{
get;
set;
}
}
When I access the cm.Current property it will return an instance of the choice class, I can now access the Text property of my choice class to see what value was selected. You will obviously have to adapt this to your particular situation. I hope this helps.
You could Try this :-
dataGridView1.CurrentRow.Cells[0].Value.ToString();
Index the column of the cell you need to look at, whichever is the index of your ComboBoxColumn.

C# Datagridview: get selected item in combobox columns

I'm working on a GUI that allows the user to manipulate xml files. I display the xml file in a datagridview organized neatly by columns through xml elements. I allow the user to add columns as an extention on my project. The column gets added to the dataset table, then updated to the datagridveiew that I use to display the xml file in. I've included the ability for the user to add a combobox column to select choices instead of entering them in constantly like.. true or false. However, that is where the problem lies. Saving a normal column was easy. The combobox column is being a pain.
I have a "save combobox column" to have it updated to the xml and a "save" button to save in a destination of the user's choice.
I've done some research and it seems like the combobox class has such a feature to gain access to the selecteditem in the combobox put in by the user.
Where we have:
ComboBox box = new ComboBox();
box.SelectedItem;
I tried applying this to the combobox column class but it does not have such a function. Thus, I cannot figure out how to directly obtain the value of the user's selected item. I tried experimenting with comboboxcell's as well, but that didn't lead me anywhere either. Both those classes I played around with do not have a... "selected item" function and even google does not have a solution for me. =( I've also tried using the cell.value, but it is "null" for some reason. Even when the user selects an item in the box, it doesn't get saved into the cell's value.
TLDR:
My question in short is, how, if possible, do you gain access to the comboboxcolumn cell's selected item? Additionally, how would you then ensure that the item value is saved in the cell?
Thanks in advance. I'm using .NET 3.5 SP1, through Visual Studio 2008 C#.
Sincerely,
tf.rz
The Control in a DataGridView is not a ComboBox, it is a DataGridViewComboBox and has different properties and methods. From MSDN
Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.
However, you mentioned that the Cell.Value is null for you. Well there may be another step you are missing according to the following article (How to: Access Objects in a Windows Forms DataGridViewComboBoxCell Drop-Down List).
You must set the DataGridViewComboBoxColumn.ValueMember or DataGridViewComboBoxCell.ValueMember property to the name of a property on your business object. When the user makes a selection, the indicated property of the business object sets the cell Value property.
If we have bound a datagridcomboboxcell with a different DisplayMember and ValueMember, like so:
dgcombocell.DisplayMember = "Name";
dgcombocell.ValueMember = "Id";
dgcombocell.DataSource = dataset1.Tables[0];
Then for getting SelectedText, and SelectedValue, we can write this code:
string SelectedText = Convert.ToString((DataGridView1.Rows[0].Cells["dgcombocell"] as DataGridViewComboBoxCell).FormattedValue.ToString());
int SelectedVal = Convert.ToInt32(DataGridView1.Rows[0].Cells["dgcombocell"].Value);
I hope it solves your problem.
Use this to get or set selected value:
object selectedValue = currentRow.Cells["comboboxColumnName"].Value
Don't forget to set DisplayMember and ValueMember for your DataGridViewComboBoxColumn
This is how it is done
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dgv.Rows[0].Cells[1];
MessageBox.Show(""+comboCell.Items.IndexOf(comboCell.Value));
A .Net combox is actually a composite control made up of a textbox and a dropdownlist. Use box.Text to get the currently displayed information.
EDIT: The row or the cell should have a .FindControl() method. You'll need to do something like:
Combobox box = (Combobox)(row.FindControl("[combobox ID]"));
string val = box.Text;
Basically, you're finding the control within its container (row or cell), then casting the control found as a combobox, then accessing its .Text property.
I use this:
private int GetDataGridViewComboBoxCellSelectedIndex(DataGridViewCell d)
{
return ((DataGridViewComboBoxCell)d).Items.IndexOf(d.Value);
}

Get DataGridView columns in order of user's ordering

I have an app that lets the user reorder columns in a DataGridView, and I want to save the "layout" upon closing the app...but it seems that when I iterate through the column collection, I get them in the order I added them, not the order they appear on screen. Is there a way to get the displayed ordering?
edit: found it, just check the DisplayIndex property of each column :)
You'll have to use the DataGridViewColumn.DisplayIndex property. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.displayindex.aspx

Categories

Resources