Selecting rows programmatically in DataGridView - c#

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.

Related

How do I hide an entire DataGridview Row if Column index 0 contains a specific string C#

What I've done so far
DataSet dataSet = new DataSet();
dataSet.ReadXml(dialog.FileName);
dataGridView1.DataSource = dataSet.Tables[0];
MessageBox.Show(this.dataGridView1.Columns["Visible"].Index.ToString());//To hide -returns 0
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells[0].Value.ToString() == "False")
{
dr.Visible = false;
}
}
The gridview
I'm trying to hide the entire Row where the Visible Column value is False
After some research, I am confident that you will be better off “filtering” the grids DataSource as opposed to setting the individual grid row’s Visible property to false.
The biggest problem you will have in doing this… is that you CAN NOT set the grids CurrentRow Visible property to false. This will throw an exception that complains along the lines of …
”Row associated with the currency manager's position cannot be made invisible”
… basically this is saying the grid's CurrentRow cannot be invisible.
Considering this, it would appear that this approach may not work since at least ONE (1) row in the grid will be the CurrentRow and your code will fail if the grid's CurrentRow “Visible” cell is set to “False.”
In addition, to exploit the testing parameters… what if ALL the rows are “False”? … In that case the exception is guaranteed since at least ONE of the rows will be the CurrentRow.
Hopefully, this may explain “why” your code may work some times and not at other times.
Therefore, I suggest a simple solution that avoids the grids currency manager all together. This can be done by filtering the grids DataSource. Something like the button click event below…
private void button1_Click(object sender, EventArgs e) {
DataView dv = new DataView(dataSet.Tables[0]);
dv.RowFilter = "Visible = True"; // <- filter rows that have True in the Visible column
dataGridView1.DataSource = dv;
}
It is unclear “where” the posted code in your question is executed, however in my solution above it will make things easier if you make dataSet or at least dataSet.Tables[0] a “GLOBAL” variable. Reason being that when you use the DataView.RowFilter and then set the grids data source to the DataView… then unless you have access to the original table dataset.Tables[0]… you will not be able to “un-filter” the grid and instead you would need to re-query the DB. I hope that makes sense. Good Luck.
The main problem here, I think, is that you are replacing the Visible value of the row, instead of the row of the Datagrid. Replace the foreach with a for:
for(int i=0; i <= dataGridView1.Rows.Count();i++) {
dataGridView1.Rows[i].Visible = Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value);
}
What is the value of dr.Cells[0].Value.ToString() when you get that row? Check it with debugger and quickwatch. Maybe is not "False" as you show it.
The main idea is get any kind of false with Convert. And also you don't need the if at all.
if (Convert.ToBoolean(dr.Cells[0].Value))
{
dr.Visible = false;
}
And also you don't need the if at all.
dr.Visible = Convert.ToBoolean(dr.Cells[0].Value);
You may use the DataGridView CellPainting event.
Everytime a cell in dataGridView1 needs repainting the event is fired.
The good thing is that this event will fire when the dataGridView1 is initialized and when the user leaves a cell. Hence this solution will remove the arbitrary rows when the DataGridView is initializing (and then remove any loaded rows with "False" in column 0) but also remove any rows that are changed to "False" by the user during run time.
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == null) //Return if cell value is null
return;
if (e.ColumnIndex == 0) //Current cell to paint is in visible column
{
DataGridViewRow currentRow = dataGridView1.Rows[e.RowIndex]; //Row of current cell
if (currentRow.Cells[0].Value.ToString() == "False")
{
currentRow.Visible = false;
}
}
}
Either add the event at the events list in the Design view or add it directly to the designer class for the control containing dataGridView1
//
// dataGridView1
//
...
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(this.dataGridView1_CellPainting);
...

How to implement GridControl with CheckBox inside it in Syncfusion using C Sharp?

I want to implement GridControl for my project but I realize Syncfusion GridControl is little more tough than Windows controls.
my requirement is like that: Suppose I have three columns and 15 rows in my gridControl and in first column of first row I want to write some hardcoded input string and in second column of first row I want to add CheckBox.
Kindly suggest me how to bind cells with CheckBox so that it would work dynamically while scrolling.
I also go through from Here:
Query 1
In first column of first row I want to write some hardcoded input string
Suggestion 1
The cell value for a particular cell can be set by using CellValue property of cell style. Please refer the below code,
this.gridControl1[1, 1].CellValue = "Sample";
Suggestion 2
The cell value can also be set by using Text property of cell style. Please make use of below code,
this.gridControl1[2, 1].Text = "Data";
Suggestion 3
To set the cell value for a particular cell, the QueryCellInfo event can also be used. Please refer below code,
//Event Triggering
this.gridControl1.QueryCellInfo += GridControl_QueryCellInfo;
//Event Customization
private void GridControl_QueryCellInfo(object sender, GridQueryCellInfoEventArgs e)
{
if(e.RowIndex==1 && e.ColIndex==1)
{
e.Style.CellValue = "Sample Name";
}
if(e.RowIndex==2 && e.ColIndex==1)
{
e.Style.Text = "Sample ID";
}
}
Query 2
In second column of first row I want to add Checkbox
Suggestion 1
To set the cell type as CheckBox for a particular cell, the CellType property can be used and the name for the CheckBox can be set by using Description property. Please refer the below code,
this.gridControl1[1, 2].CellType = GridCellTypeName.CheckBox;
this.gridControl1[1, 2].Description = "CheckBox";
The CheckBox can be checked or unchecked based on the cell value by defining the CheckBoxOptions property of the cell.
this.gridControl1[1, 2].CheckBoxOptions = new GridCheckBoxCellInfo("True","False","False",true);
this.gridControl1[1, 2].CellValue = "True";
Suggestion 2
To set Cell type as CheckBox for a particular cell, the QueryCellInfo event can also be used. Please refer the below code,
//Event Triggering
this.gridControl1.QueryCellInfo += GridControl_QueryCellInfo;
//Event Customization
private void GridControl_QueryCellInfo(object sender, GridQueryCellInfoEventArgs e)
{
if(e.RowIndex==2 && e.ColIndex==2)
{
e.Style.CellType = GridCellTypeName.CheckBox;
e.Style.Description = "CheckBox";
e.Style.CheckBoxOptions.CheckedValue = "True";
e.Style.CellValue="True";
}
}
Screenshot
Sample Link
UG Link
Dashboard sample
\Syncfusion\EssentialStudio<Installed Version>\Windows\Grid.Windows\Samples\ Cell Types\Interactive Cell Demo\CS

Reading from DataGridView

I have a DataGridViewfilled with information from my SQL:
[Its only possible to click one complete row and not only a cell, shown in my picture]
I try some Code example from: Reading data from DataGridView in C# but it dosent work for my Problem.
I try this, because it seems good
dataGridView.Rows[MyIndex].Cells["MessageHeadline"].Value.ToString();
but i get an Error.
Now i want to take the Index (add with 1, because its start with 0) and if i press on a row, my program should take the information from my DataGridViewand give it back.
Try to use CurrentRow instead of SelectedRow. The selected row only perform if you have selected row from RowHeader or the RowSelection property is set FullRowSelect. But, CurrentRow is actually focused row. You can get value even you have selected only single cell.
dataGridView.CurrentRow.Cells["MessageHeadline"].Value.ToString()
Try this:
Set the SelectionMode property of your datagridview to CellSelect. Now you will be able to select a cell itself.
And in CellMouseClick Event:
private void MyGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string FullContent = "";
for (int i = 0; i < MyGridView.Columns.Count; i++)
{
FullContent += MyGridView.Rows[e.RowIndex].Cells[i].Value.ToString() + "^";
}
FullContent = FullContent.Substring(0, Content.Length - 1);
string[] Content=FullContent.Split('^')
}
Now you can get each column content from Content array.
Like:
Content[0],Content[1],Content[2],etc.
For example, if you click the first row in your datagridview.
You can access the contents like:
FullContent; //1^Test BGW 1^Test^All^12.05.2014^.....
Splitted contents:
Content[0]; //1
Content[1]; //Test BGW 1
Content[2]; //Test
Content[3]; //All
Content[4]; //12.05.2014
just using the foreach loop can solve the problem.
foreach (DataGridViewRow row in gridStore.Rows)
{
MessageBox.Show(row.Cells[2].Value.ToString()); //row.Cell[index Here!]
}

How to get gridview cell value in RepositoryItemGridLookupEdit_ValueChanged Event and set in TextEdit?

I want to get a cell value particular focused row and previous row ?? I tried this code,
object obj1 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle - 1, gridView1.Columns["Each"]);
string str1= obj1.ToString();
textEdit1.Text = str1;
textEdit1.Text = gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Each"]);
but this code works for button but not work here in the RepositoryItemGridLookupEdit_ValueChanged Event or not work in the CustomUnboundDataEvent.
I want to get a cell value of gridview in Edit Value Change Event and then set in textEdit ? Help me.
At first this: textEdit1.Text = gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Each"]);
makes no sense, because you dont set the value of the TextEdit, just the value of the Cell. SetRowCellValue is void method!
To get the focused row and previous row, you have to handle the gridview.focusedrowchanged event. You can cast the row into value of your datasource and then assign the value to your textedit.
Example:
private void grvUebersicht_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
DataRow row = (DataRow)grvUebersicht.GetRow(e.FocusedRowHandle);
DataRow row2 = (DataRow) grvUebersicht.GetRow(e.PrevFocusedRowHandle);
TextEdit textedit = new TextEdit();
textedit.Text = row["MyColumn"].ToString();
}
Further you should think about using IList as DataSource. In my opinion it is more beautiful and modern style. If you need help iam ready to send example ;)

C#: Select row from DataGridView

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

Categories

Resources