Selecting a row in DataGridView programmatically - c#

How can I select a particular range of rows in a DataGridView programmatically at runtime?

Not tested, but I think you can do the following:
dataGrid.Rows[index].Selected = true;
or you could do the following (but again: not tested):
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}

In Visual Basic, do this to select a row in a DataGridView; the selected row will appear with a highlighted color but note that the cursor position will not change:
Grid.Rows(0).Selected = True
Do this change the position of the cursor:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Combining the lines above will position the cursor and select a row. This is the standard procedure for focusing and selecting a row in a DataGridView:
Grid.CurrentCell = Grid.Rows(0).Cells(0)
Grid.Rows(0).Selected = True

DataGridView.Rows
.OfType<DataGridViewRow>()
.Where(x => (int)x.Cells["Id"].Value == pId)
.ToArray<DataGridViewRow>()[0]
.Selected = true;

<GridViewName>.ClearSelection(); ----------------------------------------------------1
foreach(var item in itemList) -------------------------------------------------------2
{
rowHandle =<GridViewName>.LocateByValue("UniqueProperty_Name", item.unique_id );--3
if (rowHandle != GridControl.InvalidRowHandle)------------------------------------4
{
<GridViewName>.SelectRow(rowHandle);------------------------------------ -----5
}
}
Clear all previous selection.
Loop through rows needed to be selected in your grid.
Get their row handles from grid (Note here grid is already updated with new rows)
Checking if the row handle is valid or not.
When valid row handle then select it.
Where itemList is list of rows to be selected in the grid view.

Try This:
datagridview.Rows[currentRow].Cells[0];

You can use the Select method if you have a datasource:
http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx
Or use linq if you have objects in you datasource

Try this:
DataGridViewRow row = dataGridView1.Rows[index row you want];
dataGridView1.CurrentRow = row;
Hope this help!

Related

How to get IDs of only checked rows of a datagridview

I have a datagridview that contains list of subjects populated from Subject table from database.Columns include
Select(checkbox),
SubjectId,
SubjectName,
SubjectGroup.
Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database.
The problem is that the new column of checkboxes I have added to this datagridview is not being detected.
My code is:
foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
{
if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
{
olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
}
}
Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.
var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
foreach (var row in checkedRows)
{
olist.Add(row.Cells["SubjectId"].Value.ToString());
}
I realise this is an old post but I came across it and didn't think it was really answered in an efficient way so I thought I would add my method.
I have a similar block in my windows app. I read the values from the grid when the user clicks a button, and I want to know which rows they checked. As the checkboxes are in Cell 0 and the data I want is in Cell 1, I use the following code. Note the cast: it is important as it allows us the use the Where clause and therefore just a single line of code to get the collection of data. I could use the name of the cells instead of magic index numbers but then it would not fit your app so I put numbers instead (you should use names)
var checkedRows = dataGridView
.Rows
.Cast<DataGridViewRow>()
.Where(x => x.Cells[0].Value.ToString() == "1")
.Select(x => x.Cells[1]);
Note that this will give you an IEnumerable of type DataGridViewCell. If you want you can either add something like .Value.ToString() to the select or do this when you use your collection.
You question is similar to another SO question.
Check the answer of this Datagridview checkboxcolumn value and functionality.
Try this
foreach(GridViewRow r in gvSubjectsOpted.Rows)
{
GridViewCheckBoxColumn c = r.cells[0].Controls[0] as GridViewCheckBoxColumn;
if(c.Checked)
{
//Do something.
}
}
private void button1_Click(object sender, EventArgs e)
{
string subjId;
List<string> lines = new List<string>();
for (int i = 0; i < gvSubjectsList.Rows.Count; i++)
{
bool Ischecked =Convert.ToBoolean(gvSubjectsList.Rows[i].Cells["Select"].Value);
if (Ischecked == true)
{
subjId = gvSubjectsList.Rows[i].Cells["SubjectId"].Value.ToString();
lines.Add(subjId);
}
}
comboBox1.DataSource = lines;
}
//the most important thing is to set 'true' and 'false' values against newly added checkboxcolumn instead of '0' and '1'...that is,
CBColumn.FalseValue = "false";
CBColumn.TrueValue = "true";

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.

How to filter with textbox the datagrid view without datasource

The same question as here:
question
But in my case my dataGridView1.DataSource is null.
I use the dataGridView1.Rows.Add function to add rows to the table.
Is it possible to add the filter the column of dataGridView using textbox without DataSource?
Or you can use this code:
if (textBox1.Text != string.Empty)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[column_index].ToString().Trim().Contains(textBox1.Text.Trim()))
{
row.Visible = true;
}
else
row.Visible = false;
}
}
you can also try linq
private void filter()
{
if (this.txtsearch.Text != string.Empty)
this.dataGridView1.Rows.OfType<DataGridViewRow>().Where(r => r.Cells["column_name"].Value.ToString() == this.txtsearch.Text.Trim()).ToList().ForEach(row => { if (!row.IsNewRow) row.Visible = false; });
else
this.dataGridView1.Rows.OfType<DataGridViewRow>().ToList().ForEach(row => { if (!row.IsNewRow) row.Visible = true; });
}
It may be possible filter a datagrid that doesn't have a datasource, but I suspect it isn't.
Regardless, an easier solution would be to just give the grid a datasource. Rather than programmatically adding rows to the datagrid, instead create a DataTable and add rows to it, then set the grid's data source to that table. Now you can use standard filtering methods.
Insted of adding rows to the datagridview, create a DataTable and add rows to it and bind it to the datagridview. Now you can use TextBox to search.
DataTable table = new DataTable();
table.Columns.Add("Column_Name1", typeof(String));
table.Columns.Add("Column_Name2", typeof(String));
......
foreach (var element in list)
table.Rows.Add(element.Column_Name1, element.Column_Name2, ...);
dataGridView1.DataSource = table;
table.DefaultView.RowFilter = "Column_Name1 Like '"+TextBox.Text+"'";
What #Rakesh Roa M did was good, but I took it a step further to firstly make it work in VB.NET, but also so that it was case insensitive.
Like you, I'm adding content programmatically as well.
It's certainly not the best way to do this if you have thousands of entries on a DataGridView due to it's inefficiencies, but if the record set is in the hundreds, this should work fine.
If TextBox1.Text IsNot String.Empty Then
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("your_column_name").Value.ToString().ToUpper().Contains(TextBox_filter.Text.ToUpper().Trim()) Then
row.Visible = True
Else
row.Visible = False
End If
Next
End If

How to get the row index of multiple checked in checkbox column of datagridview C#

I am trying to remove a all marked/checked rows in an unbound datagridview. The checkbox column was added programatically. I know that I have to use
RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);
to remove the row from the grid. However, I am having trouble getting the row index of the multiple checked rows in the datagridview. My looping is not working. Help?
//REMOVE ALL CHECKED
foreach (DataGridViewRow ForRequestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(ForRequestRow.Cells[MarkColumn.Name].Value) == true)
{
RequestedEmpGrid.Rows[ForRequestRow.Index].Selected = true;
RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);
}
}
Why dont you try
RequestedEmpGrid.Rows.Remove(ForRequestRow)
It will just remove the row from gridview but not from Data source, so do not rebind the gridview as it will add the deleted rows again.
And if you want to delete from datasource as well just delete the selected rows from DB and then rebind the gridview.
You can try this code:
foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.Remove(requestRow);
}
}
or this:
foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.RemoveAt(requestRow.Index);
}
}
update:
How about that?
for (int i = RequestedEmpGrid.Rows.Count; i >= 0; i--)
{
var row = RequestedEmpGrid.Rows[i];
if (Convert.ToBoolean(row.Cells[MarkColumn.Name].Value))
{
RequestedEmpGrid.Rows.RemoveAt(i);
}
}

Get selected DataGridViewRows in currently displayed order

I have a DataGridView with unbound data that contains three different DataColumns. The rows can be sorted by each column, but other than that no manipulation of the displayed data is allowed.
When I query the SelectedRows property the rows are sorted in the order I initially inserted them, and not like I expected in the currently displayed or selected order. Is there a way to change this behavior?
I have same problem.
Its look the shortest way:
List<DataGridViewRow> rows =
(from DataGridViewRow row in dgv.SelectedRows
where !row.IsNewRow
orderby row.Index
select row).ToList<DataGridViewRow>();
The SelectedRows property contains the selected rows but in the reverse order and the most recent item is at the start of the list. To get the correct user selected order do the following code:
List<DataGridViewRow> dgList = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.SelectedRows)
{
dgList.Insert(0, r);
}
foreach(DataGridViewRow r in dgList)
{
//Print/consume your row here.
int selectedIndex = r.Index;
}
Note: No need to sort.
I don't think there's a one-line way to do this. You will need to redo the sort into your own list, then use IndexOf with the SelectedItems to find out the visual position.
List<DataGridViewRow> l = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.Rows)
{
l.Add(r);
}
l.Sort((x, y) =>
{
IComparable yComparable = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;
IComparable yc = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;
if (dgv.SortOrder == SortOrder.Ascending)
return yc.CompareTo(yComparable);
else
return yComparable.CompareTo(yc);
}
);
foreach(DataGridViewRow r in dgv.SelectedRows)
{
int selectedIndex = l.IndexOf(r);
}
Note the above has not been compile tested and might need some tweaking.
here is the vb.net version of the above code.
C#
List<DataGridViewRow> rows =
(from DataGridViewRow row in dgv.SelectedRows
where !row.IsNewRow
orderby row.Index
select row).ToList<DataGridViewRow>();
VB.NET
Dim rows As List(Of DataGridViewRow) = (From row As DataGridViewRow
In dgv.SelectedRows Where Not row.IsNewRow Order By row.Index).ToList()
The C# to VB.NET converters do not translate this correctly.
Hope this helps any VB.NET coder wishing to use this.
Paul
You should be able to refer to the values in the selected cell like this:
Private Sub determinePKVals(ByRef PKVal As String, ByRef PKVal2 As String, Optional ByVal row As Integer = -1)
If row = -1 Then ' optional value not passed
row = dgvDisplaySet.CurrentRow.Index
End If
PKVal = dgvDisplaySet.Rows(row).Cells(0).Value
PKVal2 = dgvDisplaySet.Rows(row).Cells(1).Value
End Sub
SelectedCells seem to be in click order or at least reverse. This one works as simple as possible:
foreach (DataGridViewRow row in dataGridLog.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected)
sb.AppendLine($"{cell.Value.ToString()}");
}
}

Categories

Resources