C#: Select row from DataGridView - c#

I have a form with a DataGridView (of 3 columns) and a Button. Every time the user clicks on a button, I want the get the values stored in the 1st column of that row.
Here is the code I have:
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in ProductsGrid.Rows)
{
if (this.ProductsGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string value = this.ProductsGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
However when I click on myButton, the this.ProductsGrid.SelectedRows.Count is 0. Also, how do I ensure that the user selects only one row and not multiple rows?
Does this code look right?

Set DataGridView.MultiSelect=false and DataGridView.SelectionMode = FullRowSelect. This will make it so the user can only select a single row at a time.

SelectedRows only returns the rows if the entire row is selected (you can turn on RowSelect on the datagridview if you want). The better option is to go with SelectedCells
private void myButton_Click(object sender, EventArgs e)
{
var cell = this.ProductsGrid.SelectedCells[0];
var row = this.ProductsGrid.Rows[cell.RowIndex];
string value = row.Cells[0].Value.ToString();
}

Well, you don't need to both iterate over all rows in your grid and access the collection of SelectedRows. If you skip iteratating and use the SelectedRows collection, then your problem is probably an incorrect SelectionMode:
The SelectionMode property must be set
to FullRowSelect or RowHeaderSelect
for the SelectedRows property to be
populated with selected rows.
(from MSDN)

You can reference the grid similar to an array:
ProductsGrid[ProductsGrid.SelectedColumns[0].Index, ProductsGrid.SelectedRows[0].Index].Value;
By selecting the indexes from the first index of the SelectedRowsCollection and SelectedColumnsCollection you'll grab the first value if multiple rows are selected.
You can lock the user to selecting only a single row by setting the MultiSelect property on the DataGridView. Alternatively you make the CellClick event perform:
ProductsGrid.ClearSelection();
ProductsGrid.Rows[e.RowIndex].Selected = true;

SelectedRows.Count returns the number of entire rows that are currently selected. You probably want to use SelectedCells.Count.

you can also use the .BoundItem

Related

Combobox dropdownlist is not filling from datagridview row

I want when I click on datagridview row then my two text boxes and combobox fill with the corresponding values but two text boxes fill accurately but category dropdown is not filling.
My C# code is
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1 && e.ColumnIndex !=-1)
{
//edit = 1;
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
proID = Convert.ToInt32(row.Cells["proIDGV"].Value.ToString());
proTxt.Text = row.Cells["nameGV"].Value.ToString();
barcodetxt.Text = row.Cells["barcodeGV"].Value.ToString();
catDD.SelectedValue = row.Cells["catIDGV"].Value.ToString();// not working properly due to which edit button is not working
// catDD.SelectedItem = row.Cells["catGV"].Value.ToString();//Also Write this line of code but not produce the desire result
MainClass.Disabled(leftPanel);
}
}
For category dropdown, which is a combo-box, to have a SelectedItem or SelectedValue you should already have all the possible categories in the "items" property, otherwise, the programming cannot select the category out of nowhere. To select items which don't exist you need to add an item first, or if you don't really need the items afterward you can just use:
catDD.Text = row.Cells["catIDGV"].Value.ToString();
Although I would not recommend doing it this way.
The other way is that you can add items by doing this (this is what I recommend):
Edit: You first add the item then select it.
string item = row.Cells["catIDGV"].Value.ToString(); // Your selected item in DataGridView
catDD.Items.Add(item); // Add the item
catDD.SelectedItem = item; // Select the item

C# - How can i get value for each column in a row on combobox value change events?

Hai everyone. For each column in a row, how can i get all the value in that columns on combobox values change events. It can be either on combobox in "Destination" or "Data_type" column. I'm think something like this example on text column:
string Source = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
string Destination = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string Similarity = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string Datatype = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
Example code or suggestion on the best way possible to this are highly appreciated. Thank you in advance.
DataGridView.CurrentCell.RowIndex
and
DataGridView.CurrentRow.Index will give you current row index irrespective of whether current control is combobox, textbox or readonly cell. use it in your logic. From name of property its obvious that it will give you current cell or row object. use it as per your need.
I prefer to use CurrentRow property because it directly gives current row object. and instead of hard coded column index in Cell property, I will prefer to use ColumnObject.Index property. so in case if we change column order, no need to change code.
For example:
string Source =
dataGridView1.CurrentRow.Cells[colSourceName.Index].Value.ToString();
(here i guess Source_Name column Name is colSourceName)
Edit:
I use it in EditingControlShowing event of DataGridView.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == colSourceName.Index)
{
((ComboBox)e.Control).SelectedIndexChanged -= cmb_SelectedIndexChanged;
((ComboBox)e.Control).SelectedIndexChanged += cmb_SelectedIndexChanged;
}
}
First it tries to detach event so if user comes 2nd time on same combobox, it do not fire it 2 time. and then re-attaching event.
You have two combobox, so you need to add condition accordingly.

Get value of a selected checkbox row in DatagridView

I have a DatagridView which contains row and data. I've added checkboxs to select one of the row (1) and then generate a PDF with the data of the selected row (2) (see picture) :
My code contains a part which check if checkbox is 1 or 0 and then I don't know how to get the data of the "checked row".. See
private void button_generer_pdf_Click(object sender, EventArgs e)
{
List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGrid_factures.Rows)
{
if (Convert.ToBoolean(row.Cells[column_action.Name].Value) == true)
{
MessageBox.Show("OK!"); // Just to check if it undestands I've checked the row
//And then here I want to get highlighted data on the screenshot to create my Pdf
}
}
//PDF Generation here
The same way you got the data from your selection column "row.Cells[column_action.Name].Value" by changing it to be the right name so maybe
row.Cells["NOM"].Value
or you can use the array number should you know it eg
rows.Cells[3].Value
hi my friend you can use this code for any cell or use a loop for all cells!!!
public void ReadDataFromDataGridView()
{
string value = dataGridView1.SelectedRows[0].Cells["columnName"].Value.ToString();
}

Selecting rows programmatically in DataGridView

I want to select row of previously selected rows after some event my code is as below.
int currentRow = dgvIcbSubsInfo.CurrentCell.RowIndex;
//code to execute
dgvIcbSubsInfo.Rows[currentRow].Selected = true;
after executing the code the preview will be as below. but i need to get the symbol > in id = 1272741 (blue selection) and not in 1272737
Probably you might have taken a look at the DataGridView.CurrentRow Property, which is a read-only property:
Gets the row containing the current cell.
But in the remarks section, there is written:
To change the current row, you must set the CurrentCell property to a
cell in the desired row.
Also, from the DataGridView.CurrentCell Property, we find out that:
When you change the value of this property, the SelectionChanged event
occurs before the CurrentCellChanged event. Any SelectionChanged event
handler accessing the CurrentCell property at this time will get its
previous value.
So, there is no need that you actually select the currentRow becasue it will be selected when you set the CurrentCell value (unless you have some code to be executed inside the current scope between the SelectionChanged and CurrentCellChanged events). Try this:
//dgvIcbSubsInfo.Rows[currentRow].Selected = true;
dgvIcbSubsInfo.CurrentCell = dgvIcbSubsInfo.Rows[currentRow].Cells[0];
I think you wish to highlight the row. Please try following code, I think it might help:
Color color = dgv.Rows[prevRowIndex].DefaultCellStyle.SelectionBackColor;
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = color;
Try the following to change the current row. Since the OP is a little unclear as to what row should be the new row, my example simply shows moving from the current row to the previous row (if there is a previous row). The first line of code is optional. You can also hardcode col to 0 (or some other column) to use a fixed column if you don't want to use FullRowSelect.
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
int row = dataGridView.CurrentCell.RowIndex;
int firstRow = dataGridView.Rows.GetFirstRow(DataGridViewElementStates.None);
if (row != firstRow)
{
row--;
int col = dataGridView.CurrentCell.ColumnIndex;
dataGridView.CurrentCell = dataGridView[col, row];
}
I came here wanting to learn how to programmatically select rows in a DataGridView control. Here is how to select the top row in your DataGridView control named dg1 and "click" it:
dg1.Rows[0].Selected = true;
dg1_RowHeaderMouseClick(null, null);
This then calls the following event which is expecting one selected row.
private void dg1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var selectedRows = dg1.SelectedRows;
// Make sure we have a single row selected
int count = selectedRows.Count;
if (count == 1)
{
tbAssemblyName.Text = dg1.SelectedRows[0].Cells[0].Value.ToString();
}
}
I had everything working when the user clicked the row they wanted. When there was only one record to choose from I wanted to "click" it for the user.

Select newly added Row - DataGridView and BindingSource

I'm adding a new Row to a BindingSource that is Bound to a DataGridView
source.AddNew();
After this, use BindingSource to get the newly added row is return the next row in the DataGridView when its sorted.
ROW "A"
ROW "B" <- myBindingSource.AddNew();
ROW "C"
myBindingSource.Current gives ROW "C". (it became the selected row in the DataGridView)
I need this because I want to update just the newly added row
DataRowView drv = (DataRowView)myBindingSource.Current;
myTableAdapter.Update(drv.Row);
and not the entire table.
myTableAdapter.Update(myDataSet.myTable);
and also, I would like to have this newly added line selected in the DataGridView after insertion.
is it possible in some way?
Use the events from the DataGridView like this for this task:
private void RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
this.Rows[e.RowIndex].Selected = true;
}
That marks the newly added row as the selected.
Is it possible? I would say yes.
Here's an aricle related to it:
DataGridView and BindingSource (on Joel's Forum)
Dont know id its the best solution but for instance looks better than iterate.
DataRowView drv = (DataRowView)source.AddNew();
grupoTableAdapter.Update(drv.Row);
grupoBindingSource.Position = grupoBindingSource.Find("ID", drv.Row.ItemArray[0]);
You've already identified one way to accomplish this. Another way to accomplish it is to ignore the UI completely:
foreach (DataRow r in myTable.AsEnumerable().Where(x => x.RowState == DataRowState.Added))
{
myTableAdapter.Update(r);
}
Of course, this calls Update on all added rows in the table, not the one that was just added, so if you have some crazy scenario where you have two different ways of adding new rows to the table it won't work.
Extending from Oliver Friedrich's answer, the function when created using the controls's property as shown in the designer will look like:
private void drv_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
drv.Rows[e.RowIndex].Selected = true;
}

Categories

Resources