c# how i can get selected rows name of gridcontrol devexpress - c#

i want get rows values by clicked the row. How i can get rows name of GridControl?
private void btnMusteriDuzenle_Click(object sender, EventArgs e)
{
int[] celRows = ((GridView)grdMusteriListele.MainView).GetSelectedRows();
MessageBox.Show(selRows.ToString());
}

The GetSelectedRows method returns handles of the selected rows.
To retrieve row cell values, utilize the following API: GetRowCellValue, GetRowCellDisplayText:
int[] selectedRows = gridView.GetSelectedRows();
for(int i = 0, i < selectedRows.Length, i++){
int id = (int)gridView.GetRowCellValue(selectedRows[i], "Id");
//...
}
If you are using the single-selection mode(the OptionsSelection.MultiSelect property is false) you can use the following API to obtain cell values of a focused row: GetFocusedRowCellValue, GetFocusedRowCellDisplayText. These API utilized the handle of a currently focused row via the FocusedRowHandle property:
int focusedId = (int)gridView.GetFocusedRowCellValue("Id");
To learn more, take a look at Accessing Rows in Code. Row Handles help article.

Related

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

Exclude the Totals Row from sorting a bound DataGridView

I am showing a Totals Row as last row. I want to exclude that row from sorting when the user clicks on the column header. By using sql union I am adding total column to my result. I am using SQL, C# and DataGridView control. I am not able to expose ColumnHeader_Click event. I am only using TableStyle[0].AllowSorting = false. How can I apply that custom sorting on the control?
Thanks
Thanks TaW, your answer helped me. My needs were a little different, I needed the Total to appear at the top and also retain the sort column throughout as my grid is highly interactive with loads of filtering and changes in the data being presented.
My sorting is done via
protected void ReportGridView_Sorting(object sender, GridViewSortEventArgs e)
Here's what I ended up using in my method to populate the GridView:
if (!myDataTable.Columns.Contains("SortLevel"))
{
myDataTable.Columns.Add("SortLevel", typeof(Int16));
foreach (DataRow dr in myDataTable.Rows)
{
dr["SortLevel"] = 0;
}
dt.Rows[0]["SortLevel"] = 1;
}
if ((Session["SortDirection"] != null) && (Session["SortExpression"] != null))
{
myDataTable.DefaultView.Sort = "SortLevel DESC, " + Session["SortExpression"] + " " + Session["SortDirection"];
}
MyGridView.DataSource = myDataTable;
MyGridView.AllowSorting = true;
MyGridView.DataBind();
Side note: I had to use Sessions to hold the custom sorting instead of ViewState as this wasn't working properly with the dynamically created buttons in my gridview
This solution is based on #T.S.'s suggestion but works directly in the DataSet, not in SQL.
I have tested it in VS2013; I don't know if it will work in .Net 1.1 and would have to revive a very old machine to test that..
I don't know what you mean by
I am not able to expose columnheader_click event.
I have split the solution into a function and the ColumnHeaderMouseClick event; if you really can't use that event you will have to find another way; but one way or the other you need to trigger the sort and decide by which column(s) to sort.
The heart of the solution are the setting of the new column values and the expression by which you identify your 'TotalsRow'. I have used my test table's PK column 'ID' and push the 'ID=1 record' to the bottom. After setting the sort column to 0 on all rows the first row to fit the expression is set to maxInt.
You will have to adapt that to an expression that works for your result set.
I am adding and setting the custom sort column dynamically and remove it after the sort; the DGV is suspending its layout until the whole affair is completed.
DataTable yourTable = ..
private void dataGridView1_ColumnHeaderMouseClick(object sender,
DataGridViewCellMouseEventArgs e)
{
string col = dataGridView1.Columns[e.ColumnIndex].Name;
if (col != "") sortDGV (col );
}
private void sortDGV(string col)
{
dataGridView1.SuspendLayout();
yourTable.Columns.Add("sortMe", typeof(Int32));
yourTable.DefaultView.Sort = col;
DataRow[] dr = yourTable.Select("ID='1'");
for (int r = 0; r < yourTable.Rows.Count; r++) yourTable.Rows[r]["sortMe"] = 0;
dr[0]["sortMe"] = int.MaxValue;
yourTable.DefaultView.Sort = "sortMe," + col;
yourTable.Columns.Remove("sortMe");
dataGridView1.ResumeLayout();
}
Although 8 years old, I came across this desire myself but had a different solution: I wanted the last Row to be an "Editing Row" which would always remain at the bottom regardless of sorting.
So, create a DataGridViewRow separate from the regular data grid, add it after filling the DGV. Before sorting, remove the Row from the DGV, then add it again after sorting. I used Clicking on the RowHeaderText to trigger the sort (manual sort using a private class comparer for the sorting, and the DGV_Sort event to indicate sorting has completed. (You have to keep track of when you enter this event as I found it enters before and after sorting - so I used a form global boolean to keep tack of that.
I keep track of any editing on my 'my Removeable Row' separately, but you can always just Clone the row before removing if you don't want to do that.
Note that I have AllowUserToAddRows = true when I start, but after I programmatically fill the grid, I switch it to false, to prevent the addition of more 'editable' rows beneath my 1 row edit at a time desire. I have a button to add the row to the DGV when finished editing, at which time I just create a new myRemovableRow and add that row to the DGV.
Public partial class Form1 : Form
{
public DataGridViewRow myRemoveableRow;
public bool bDoingSort = false;
.
.
private DataGridViewRow CreateNewBlankRow()
{ // create your a new row with whatever default values for DGV
DataGridViewRow newRow = (DataGridViewRow) DGV.Rows[0].Clone();
// or however you want to create your row and fill in default values
return newRow;
}
private void FillDGV()
{
// Do whatever to fill your DataGridView (called DGV here)
myRemoveableRow = CreateNewBlankRow();
DGV.Rows.Add(myRemoveableRow);
}
private void DGV_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
bDoingSort = true;
DGV.Rows.Remove(myRemoveableRow);
SortOrder dir = SortOrder.Ascending; // or whatever logic you use
.
DGV.Sort(new RowComparer(dir, e.ColumnIndex));
}
private void DGV_Sorted(object sender, EventArgs e)
{ // 'Sorted' Event from the DataGridView events
if (bDoingSort)
{
DGV.Rows.Add(myRemoveableRow);
bDoingSort = false; //reset sorting boolean
}
else // we haven't set the sorting up yet
{
return;
}
}
// setup manual sorter (I use separate Classes for int, string, double etc)
private class RowComparer : System.Collections.IComparer
{
private static int sortOrderModifier = 1;
private readonly int Column;
public RowComparer(SortOrder sortorder, int iColumn)
{
if (sortOrder == SortOrder.Descending)
sortOrderModifier = -1;
else
sortOrderModifier = 1;
this.Column = iColumn;
}
public int Compare (Object objA, Object objB)
{
DataGridViewRow row1 = (DataGridViewRow)objA;
DataGridViewRow row2 = (DataGridViewRow)objB;
// do your sort compare (for eg.)
return sortOrderModifier * (row1.Cells[Column].Value).CompareTo(row2.Cells[Column].Value);
}
}
}
I find this works well - I not only sort but filter (out) entries on the fly. (VS 2022)

How to get field value of selected Row Devexpress GridView?

I use a DevexpressGridView to display all TOPIC (id,title,content)
<dx:ASPxGridView ID="gv" runat="server"
OnSelectionChanged="gv_SelectionChanged" >
I have grid_SelectionChanged event:
protected void gv_SelectionChanged(object sender, EventArgs e)
{
int id= selected row...???; //how can I get the value of selected row
string sql = "select * from TOPIC where idTOPIC="+id;
DataTable topic = l.EXECUTEQUERYSQL(sql);
TextBox1.Text = topic.Rows[0][1].ToString();
}
...
It seems gv.SelectedRow method isn't exist in DevGridview.
As recommended, I've tried with FocusedRowIndex method, but I really dont know the right syntax to get the value of selected row.
Help!!!
Changing the selection is different from changing the focused row. See the documentation for Selection for the difference between the two.
You can use gv.GetSelectedFieldValues to get the rows which are selected.
var ids = gv.GetSelectedFieldValues("id");
foreach( var id in ids )
DoSomethingWithObject(id);
You should handle the FocusedRowChanged event if you're interested in the focused row.
You can use the FocusedRowIndex value to index the rows of gv.DataSource, for example:
DataTable ds = (DataTable)gv.DataSource;
var id = ds.Rows[gv.FocusedRowIndex]["id"];
or you can use var id = gv.GetRowValues(gv.FocusedRowIndex, "id").
I've found my answere here after a long time searching google:
http://www.devexpress.com/Support/Center/Question/Details/Q347704
Use the ASPxGridView.GetSelectedFieldValues method get selected row values on the server side.
You can also get selected data row as
int rowHandle = gridView1.FocusedRowHandle;
if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
{
return this.gridView1.GetDataRow(rowHandle);
}
This would return DataRow
Please note this is when I am using Devexpress gridControl in WinForms
If you want to get only ID field value you can use this
int id = Convert.ToInt32(gv.GetRowValues(gv.FocusedRowIndex, "ID").ToString());
if you have an object you can use this
Personels selectedPersonel = gv.GetRow(gv.FocusedRowIndex) as Personels;
and get value method is
int ID = selectedPersonel.ID;

Unable to get DatagridView to select proper row

I cannot understand what is happening here:
void FindRecord(string pRecordID){
dgv_cusData.ClearSelection();
for(int i=0;i < dgv_cusData.Rows.Count;i++){
if (dgv_cusData.Rows[i].Cells["recordid"].Value.ToString()==pRecordID){
dgv_cusData.CurrentCell = dgv_cusData.Rows[i].Cells[1];
dgv_cusData.Rows[i].Selected = true;
}
}
}
pRecordID is a unique column in the DGV. I only have three records in the grid and I know that the selected record is in position 2; however then the SelectionChanged event fires:
void Dgv_cusDataSelectionChanged(object sender, EventArgs e)
{
MessageBox.Show(dgv_cusData.CurrentCell.RowIndex.ToString()); // <---- Returns 0;
lbl_DetailsLabel.Text = "Details For "+dgv_cusData.CurrentRow.Cells[1].Value;
}
The CurrentCell.RowIndex always returns 0. Am I missing something while trying to select a current row in the DGV? Any help would be appreciated. Cheers!
I wonder if selecting the row is was causes you to lose the CurrentCell.
Does the row highlight in the datagridview?
Do you allow multiple row selections on the grid. If not I think you would get better results with the following:
MessageBox.Show(dgv_cusData.SelectedRows[0].Index.ToString());
And:
lbl_DetailsLabel.Text = "Details For "+ dgv_cusData.Rows(dgv_cusData.SelectedRows(0).Index).Cells[1].Value;

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