How to get the selected row values of DevExpress XtraGrid? - c#

Consider the following picture
I get the selected row values in the three textboxes shown in the figure when i click a cell using following code.
void dataGridView1_CellClick_1(object sender, DataGridViewCellEventArgs e) {
TBGRNo.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
TBSName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
TBFName.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
My Question is: how will I do the same thing in DevExpress XtraGrid control??

Here is the way that I've followed,
int[] selRows = ((GridView)gridControl1.MainView).GetSelectedRows();
DataRowView selRow = (DataRowView)(((GridView)gridControl1.MainView).GetRow(selRows[0]));
txtName.Text = selRow["name"].ToString();
Also you can iterate through selected rows using the selRows array. Here the code describes how to get data only from first selected row. You can insert these code lines to click event of the grid.

You can do this in a number of ways. You can use databinding (typical initialized after InitializeComponent();)
textBox1.DataBindings.Add(new Binding("Text", yourBindingSource,
"TableName.ColumnName", true, DataSourceUpdateMode.OnPropertyChanged));
or use a DataLayoutControl (if you are going to use textbox for editing, I really recommend spending some time to learn how to use this component.
or in FocusedRowChanged by assigning from one of these methods:
textBox1.Text = gridView1.GetDataRow(e.FocusedRowHandle)["Name"].ToString();
textBox1.Text = gridView1.GetFocusedDataRow()["Name"].ToString();
textBox1.Text = (gridView1.GetFocusedRow() as DataRowView).Row["Name"].ToString();
textBox1.Text = gridView1.GetFocusedRowCellValue("Name").ToString();

I found the solution as follows:
private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
TBGRNo.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "GRNo").ToString();
TBSName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SName").ToString();
TBFName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FName").ToString();
}

Which one of their Grids are you using? XtraGrid or AspXGrid? Here is a piece taken from one of my app using XtraGrid.
private void grdContactsView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
_selectedContact = GetSelectedRow((DevExpress.XtraGrid.Views.Grid.GridView)sender);
}
private Contact GetSelectedRow(DevExpress.XtraGrid.Views.Grid.GridView view)
{
return (Contact)view.GetRow(view.FocusedRowHandle);
}
My Grid have a list of Contact objects bound to it. Every time a row is clicked I load the selected row into _selectedContact. Hope this helps. You will find lots of information on using their controls buy visiting their support and documentation sites.

For VB.Net
CType(GridControl1.MainView, GridView).GetFocusedRow()
For C#
((GridView)gridControl1.MainView).GetFocusedRow();
example bind data by linq so use
Dim selRow As CUSTOMER = CType(GridControl1.MainView, GridView).GetFocusedRow()

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.
For example:
private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
return;
MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());
}

var rowHandle = gridView.FocusedRowHandle;
var obj = gridView.GetRowCellValue(rowHandle, "FieldName");
//For example
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));

Related

Display cell value on textbox in c#

My problem is that it will only display the contents of datagrid on textboxes when i click on the cells under Price column which has a Money DataType all others except for ItemNo is Varchar(100). Please help, thanks
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow row = this.dataGridView1.CurrentRow;
txtDsc.Text = row.Cells["Description"].Value.ToString();
txtQty.Text = row.Cells["Qty"].Value.ToString();
txtUnt.Text = row.Cells["Unit"].Value.ToString();
txtPrc.Text = row.Cells["Price"].Value.ToString();
txtRmr.Text = row.Cells["Remarks"].Value.ToString();
}
As the other answer pointed out the code seems to be working fine.
I suspect the event is not firing off. Try putting in a breakpoint and investigate that bit.
I am presuming you need CellClick instead of CellContentClick.
Refer CellContentClick event doesn't always work
Alternatively if you are trying to display the text box values based on the selection on the data grid view, use DataGridView.SelectionChanged Event
I'm not entirely sure why it is only populating when you click that cell; I recreated your code and it works just fine. I did manage to recreate it again using the following code:
private void myDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int row = myDGV.CurrentCell.RowIndex;
txtDsc.Text = myDGV.Row[row].Cells["Description"].Value.ToString();
txtQty.Text = myDGV.Row[row].Cells["Qty"].Value.ToString();
txtUnt.Text = myDGV.Row[row].Cells["Unit"].Value.ToString();
txtPrc.Text = myDGV.Row[row].Cells["Price"].Value.ToString();
txtRmr.Text = myDGV.Row[row].Cells["Remarks"].Value.ToString();
}

Set DataGridViewComboBox default equal to existing DataGridView column

I have added a DataGridViewComboBox to a bound DataGridView (grdBOOK), the DataGridViewComboBox will replace column 3 to allow for user selection. I'm struggling to set the default of the DataGridViewComboBox equal to the value of column 3 so user selection is not required if the value is correct.
I pulled the code below from the net, but I get an error:
DataGridViewComboBoxCell value is not valid.
I thought a ComboBox cell could be treated as a normal DataGridView cell, but (see code below) an error is generated when a string is added to the ComboBox column? I've trawled the net and SO for a few days but nothing works, any suggestions please?
public void BOOK_COMBO2()
{
DataGridViewComboBoxCell cb_cell = new DataGridViewComboBoxCell();
DataGridViewComboBoxColumn cb_col = new DataGridViewComboBoxColumn();
// Contract field
cb_col.Items.AddRange("YEARLY", "MONTHLY", "");
cb_col.FlatStyle = FlatStyle.Flat;
cb_col.HeaderText = "newCONTRACT";
cb_col.Width = 50;
cb_col.ValueType = typeof(string);
// Add ComboBox and test
grdBOOK.Columns.Insert(5, cb_col);
grdBOOK.Rows[14].Cells[4].Value = "zzz"; // No error adding string to normal dgv column
grdBOOK.Rows[14].Cells[5].Value = "xxx"; // Error adding string to dgvcombobx column
//copy old values to new combobox and set as default
foreach (DataGridViewRow item in grdBOOK.Rows)
{
item.Cells[5].Value = item.Cells[3].Value;
}
//hide original column
grdBOOK.Columns[3].Visible = false;
}
After more research on the net, IMHO using a ContextMenuStrip is a better method of achieving this. Link here. A ContextMenuStrip has better methods, events, properties etc. I hope this helps others looking for a solution.
private void dataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
// If the data source raises an exception when a cell value is
// commited, display an error message.
if (e.Exception != null &&
e.Context == DataGridViewDataErrorContexts.Commit)
{
MessageBox.Show("");
}
}
private void Form1_Load(object sender, EventArgs e)
{ dataGridView1.DataError +=
dataGridView1_DataError;}

How to create subcolumns in RadGridView?

I have 2 RadGridViews. A GridView with packages and a GridView with detail information.
I use Winforms and the RadGridView of Telerik.
I have source like this
private void CreatePackages()
{
var datasource = from s in Something....;
gvPackages.Columns["colType"].IsVisible = false;
gvPackages.GroupDescriptors.Clear();
if ((int)cbddlPackageType.SelectedValue == -1)
{
GroupDescriptor descriptorType = new GroupDescriptor();
descriptorSoort.GroupNames.Add("colType", ListSortDirection.Ascending);
gvPackages.GroupDescriptors.Add(descriptorType);
}
gvPackages.DataSource = datasource;
}
...
private void gvPackages_SelectionChanged(object sender, EventArgs e)
{
OpenDetails(CurrentId);
}
I want to create a grid with the detail information in the same gridview
How do you do that?
Like this:
Well, it's a bit too late I guess. Anyway, maybe this helps some other devlopers facing the same problem.
I think you're looking for Templates. You could add a template in two ways:
1st (in designer):
Click on the three dots in your RadGridView.Templates property.
And then click on "Add".
2nd (programmatically):
GridViewTemplate template = new GridViewTemplate();
radGridView1.Templates.Add(template);
Now once you have added your template to your RadGridView, you can use it with its index like:
GridViewTemplate myTemplate = radGridView1.Templates[0];
Now you can use it as a "normal" RadGridView and e.g. set its DataSource property.
myTemplate.DataSource = lFooBar;

How to update the value of a Label in footer template of a gridview?

I have a Gridview that has editable fields in it am calculating the sum of every column and displaying it in the footer columns my gridview column looks like
This is not updating the value can anyone please help me where i should correct my code?
if (i == objGrid.rows.length)
{
objGrid.rows[i].cells[2].children[0].innerText = ClsSum;
objGrid.rows[i].cells[3].children[0].innerText = NonSaleSum;
objGrid.rows[i].cells[7].children[0].innerText = SecSum;
}
You can check for the rows.length -1.
And make sure that the code snippet will get executed after the postback.
I hope this code executes after you bind your gridview . So please check if you have applied
(!IsPostBack) in your GridviewBind method .
Also check does if your code reaches this method when reloads or updates your values ?
You can try this also, put below code out side of loop
//create css class called "footerClass" and apply on column fotter template
var objGrid= document.getElementById('<%=YourGrid.ClientID%>');
var cells = objGrid.getElementsByClassName('footerClass')
cells[0].innerText = ClsSum;
cells[1].innerText = NonSaleSum;
cells[2].innerText = SecSum;
I hope you are using Grid_RowDataBound() event and accordingly that you can try this
protected void Grid_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
e.Row.cells[2].children[0].innerText = ClsSum;
e.Row.cells[3].children[0].innerText = NonSaleSum;
e.Row.cells[7].children[0].innerText = SecSum;
}
}

Can I make row cell value readOnly on XtraGrid just for one row?

How can I make a specific row cell readonly(not editable) on XtraGrid? For example just for row[0] but not all rows.
You can use the GridView.CustomRowCellEdit event:
//...
var repositoryItemTextEditReadOnly = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
repositoryItemTextEditReadOnly.Name = "repositoryItemTextEditReadOnly";
repositoryItemTextEditReadOnly.ReadOnly = true;
//...
void gridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e) {
if(e.RowHandle == 0)
e.RepositoryItem = repositoryItemTextEditReadOnly;
}
You can use the ColumnView.ShownEditor event:
void gridView1_ShownEditor(object sender, EventArgs e)
{
ColumnView view = (ColumnView)sender;
view.ActiveEditor.Properties.ReadOnly = view.FocusedRowHandle == 0;
}
Source: How to Conditionally Prevent Editing for Individual Grid Cells
When you need to make a grid cell read-only based on a condition, the
best approach is to use the ShowingEditor event of the
GridView and prevent editing via the e.Cancel parameter passed to the event. Simply set it to True when it is necessary to prevent
editing.
// disable editing
private void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e) {
GridView view = sender as GridView;
e.Cancel = view.FocusedRowHandle == 0;
}
Source - How to display disabled buttons for particular cells within a ButtonEdit column
Another approach is that assign a read only repository editor control as #DmitryG suggested and I have also implement that way some times when there was a column which contains a button.
In your case you should create two TextEdit repository items. One with
the enabled button and another with the disabled button. Then handle
the GridView.CustomRowCellEdit event and pass the necessary
repository item to the e.RepositoryItem parameter according to a
specific condition. Please see the Assigning Editors to Individual
Cells help topic for additional information.
private void gridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
if (e.Column.Caption == "Any2")
{
if (e.RowHandle == 0)
e.RepositoryItem = columnReadOnlyTextEdit;
else
e.RepositoryItem = columnTextEdit;
}
}
References:
How to customize the Look-And-Feel of my grid cells
How to make my grid columns read-only

Categories

Resources