Is there a way to use OnMouseOver to select a radgrid row? - c#

I am currently highlighting a row in a radgrid using OnMouseOver. I would like to know if it is possible to use OnMouseOver to select the row rather than highlight it.
Alternatively, I would like the highlighted row to remain highlighted if the radgrid loses focus, such as when a confirmation box pops up.
Thanks in advance.

According to Telerik documentation, it should be possible to select the item OnMouseOver using the following code (if you don't have any detail tables you can nix the if statement and just use the code from the else block to find the currentDataItem):
function RadGrid1_RowMouseOver(sender, eventArgs) {
var currentDataItem = null;
// clear all currently selected items before selecting new
sender.get_masterTableView().clearSelectedItems();
if (eventArgs.get_itemIndexHierarchical().indexOf(':') > 0)
{
var detailTableIndex = eventArgs.get_itemIndexHierarchical().split(':')[0];
var rowIndex = eventArgs.get_itemIndexHierarchical().split(':')[1].split('_')[1];
currentDataItem = sender.get_detailTables()[detailTableIndex].get_dataItems()[rowIndex];
}
else
{
currentDataItem = sender.get_masterTableView().get_dataItems()[eventArgs.get_itemIndexHierarchical()];
}
if (currentDataItem != null)
{
currentDataItem.set_selected(true);
}
}

The other answers here do not work with the WPF Telerik RadGridView as we don't have access to RowMouseOver event.
For a WPF Telerik RadGridView, the best approach if the grid doesn't contain UI elements is to use ChildrenOfType<> in a Linq expression with IsMouseOver.
private void myGridView_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
MyCustomClass myClass = null;
var rows = this.myGridView.ChildrenOfType<GridViewRow>().Where(r => r.IsMouseOver == true);
foreach (var row in rows)
{
if (row is GridViewNewRow) break;
GridViewRow gvr = (GridViewRow)row;
myClass = (MyCustomClass)gvr.Item;
}
// do something with myClass here if we have found a row under mouse
}

Thanks! Your solution worked great, but rows would not become unselected when mousing over another row even if AllowMultiRowSelection was set to False. The following code will select a single row in the radgrid when the mouse hovers over the row:
<script type="text/javascript">
function grdUsers_RowMouseOver(sender, eventArgs) {
var NumberItems = sender.get_masterTableView().get_dataItems().length;
for (var count = 0; count < NumberItems; count++) {
var currentDataItem = sender.get_masterTableView().get_dataItems()[count];
if (count == eventArgs.get_itemIndexHierarchical()) {
currentDataItem.set_selected(true);
}
else {
currentDataItem.set_selected(false);
}
}
}
</script>
I called the function at the following location:
<ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True">
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowMouseOver="grdUsers_RowMouseOver" />
</ClientSettings>

Related

DataGrid Select Cells in only one Row

Is there a way to let the user only select one row in a datagrid
For example that should the user can do:
That he should can't do:
i saw this but it dont see how to use that for my problem:
https://stackoverflow.com/a/3072929/1764978
I wanted to use the SelectionChanged on the DataGrid, but it doesnt trigger when i change selected cells, just only SelectedCellsChanged and there is no Handled-Property
Edit
When im using ethicallogics solution i got:
I select a full row.. thats not what i want
This might be optimized, but this worked for me.
It keeps track of the first selected item, meaning the row, and if there is a selection outside of that row, it removes the whole selection (and replaces it with the newly selected cell). It could be enhanced, probably, to restore the initial selection, but my usecase didn't need that.
Anyway, see if this works for you.
private object selectedItem;
private void DataGrid_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
var dg = (sender as DataGrid);
if (selectedItem == null)
selectedItem = e.AddedCells.First().Item;
var allInSameRow = e.AddedCells.All(info => info.Item == selectedItem);
if (!allInSameRow)
{
dg.SelectedCells.Clear();
selectedItem = null;
}
}
If my guess is correct : you want is
1) Allow the user to select one cell from the whole grid.
2) After first selection you want the user not to select any cells from any other row.
3) If user wants to select multiple cells then he is allowed to do so but in the same row in which he has selected the first cell.
I don't know the exact solution or I don't have any code to guide you.
But If you can then disable other rows at the time of first selection.
int _selectedRow = -1;
int _selectedColumn = -1;
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
switch (dataGridView1.SelectedCells.Count)
{
case 0:
// store no current selection
_selectedRow = -1;
_selectedColumn = -1;
return;
case 1:
// store starting point for multi-select
_selectedRow = dataGridView1.SelectedCells[0].RowIndex;
_selectedColumn = dataGridView1.SelectedCells[0].ColumnIndex;
return;
}
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
if (cell.RowIndex == _selectedRow)
{
if (cell.ColumnIndex != _selectedColumn)
{
_selectedColumn = -1;
}
}
else if (cell.ColumnIndex == _selectedColumn)
{
if (cell.RowIndex != _selectedRow)
{
_selectedRow = -1;
}
}
// otherwise the cell selection is illegal - de-select
else cell.Selected = false;
}
}
Try this
<DataGrid SelectionMode="Single" SelectionUnit="Cell"
I am currently working on something like that and I am creating string variables for every record that I want to take. I use this line of code:
string somename = ((DataRowView)DataGridName.SelectedItem).Row["ColumnName"].ToString();
this code will take only one cell (it depends of the ColumnName which record will be stored in the variable) from the row the user selected.

Show the page with particular item in RadGrid

I have a RadGrid that I supply with data using DataSourceID. The RadGrid has paging, and I want to show the page containing some particular item. To do this, I find the offset of the item in the data and set the page number:
var index = dataSource.Count(t => t.Id > _selectedTickId);
var page = index / rgTicks.PageSize;
rgTicks.CurrentPageIndex = page;
My question is where to put this code. In the OnDataBound I don't seem to have access to the data source. If I put it in the OnSelecting the retrieving of data has a side effect of setting the page number. Should I extend the GridTableView to implement this functionality? Which method should I override?
I will suggest to compute index value in OnSelecting (which is data dependent) while page index can be set in OnDataBound or PreRender event.
My usecase was to jump to an item that was just inserted using a popup editor. Here's how I solved it. I am omitting non relevant properties in the tag. All the data wiring is up to you, but here are the relevant bits. Important: use DataKeyNames to avoid messy digging in the GridDataItem for a value.
In the page I have:
<telerik:RadGrid ID="rgItems" runat="server" AllowPaging="true"
OnNeedDataSource="rgItems_NeedDataSource"
OnPreRender="rgItems_PreRender"
OnInsertCommand="rgItems_InsertCommand">
<MasterTableView
CommandItemDisplay="Top"
CommandItemSettings-AddNewRecordText="Add New Item"
CommandItemSettings-ShowAddNewRecordButton="True"
DataKeyNames="IntItemId"
EditMode="popup"
EditFormSettings-PopUpSettings-Modal="true">
And in code behind:
private bool itemInserted = false;
protected void rgItems_InsertCommand(object sender, GridCommandEventArgs e)
{
itemInserted = true;
}
protected void rgItems_PreRender(object sender, EventArgs e)
{
if (itemInserted)
{
// Select the record and set the page
int LastItem = 0; // Put code to get last inserted item here
int Pagecount = rgItems.MasterTableView.PageCount;
int i = 0;
GridDataItem GDI = null;
while (i < Pagecount)
{
rgItems.CurrentPageIndex = i;
rgItems.Rebind();
GDI = rgItems.MasterTableView.FindItemByKeyValue("IntItemId", LastItem);
if (GDI != null) break; // IMPORTANT: Breaking here if the item is found stops you on the page the item is on
i++;
}
if (GDI != null) GDI.Selected = true; // Optional: Select the item
itemInserted = false;
}
}

Question about checkbox and datagridview

I have datagridview with checkbox column, and the checkbox within the column can be checked or unchecked with external checkbox. It works fine while selecting all the columns and saving the data in database. But, when I unchecked the checkbox in the datagridview with external checkbox and again select the single checkbox within the datagridview, it again takes the rowindex of all the checkbox within the column.
if (chkbranches.Checked == true)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = true;
}
for (int i = 0; i < gridviewholiday.Rows.Count; i++)
{
rowindex = i;
list.add(rowindex);//to put the rowindex in array list
}
}
else if (chkbranches.Checked == false)
{
foreach (DataGridViewRow dr in gridviewholiday.Rows)
{
dr.Cells[0].Value = false;
gridviewholiday.Refresh();
gridviewholiday.ClearSelection();
list.Clear();
}
}
Why do you loop twice if chkbranches is checked? Can't you add items to the list within the first foreach? And in the loop for unchecking, why do you refresh, and clear both controls each time? Probably only needed once.
And as mentioned, this isn't doing anything about single checks. If you're expecting it to, that seems to be the problem.
Not quite sure what your attempting to do, but I have something similar with a button that deletes all the checked rows. I use a template field like so for the check box:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Then for the Delete button code behind I do:
protected void btnDeleteChecked_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gridOrders.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("cbSelector");
if ((null != cb) && cb.Checked)
{
uint id = Convert.ToUInt32(gridOrders.DataKeys[row.RowIndex].Value);
gInvoiceDB.DeleteInvoice(id, true);
}
}
}

How to Get cell index in gridview

I'm using a website(asp.net,C#) to view some details in gridview. In that gridview I have generated checkboxes dynamically. So it will be placed any cell inside of that gridview. I find that control in grdview by using FindControl(), but I cant get that cell index... now I want to get that excact cell index which placed that checkbox. How shall I get that cell index?
Please anyone Tell me the solution of this problem.
Thanks in advance.
My code for getting that Control is:
if (HeaderCell.Text.Contains(strColumnName))
{
CheckBox chk = GrdDynamicControls.Rows[index].FindControl(chkCheckBox1.ID) as CheckBox;
chk.Checked = true;
strCelValue = chk.Checked.ToString();
}
Try this:
int theCellNumberWhatINeed = -1;
for (int cellNumber = 0; cellNumber < GridView1.Rows[index].Cells.Count; cellNumber++)
{
foreach (Control ctrl in GridView1.Rows[index].Cells[cellNumber].Controls)
{
if (ctrl.ID == "aCheckBox") // or compare by clientid... etc
{
theCellNumberWhatINeed = cellNumber;
break;
}
}
}
if (theCellNumberWhatINeed > -1)
{
// ...
}
Not the most elegant solution but works with the builtin gridview control without creating your own.
You can use Event Args e
e.Item.ItemIndex
it will return an integer
Hope this will help

C# dynamically taking data from DataGridView

I'm trying to get my current program to take information from a dynamically created DataGridView. I have managed to get the information into the grid, and perform the required search, however now I'm really stuck.
I have added a column to the datagridview which holds a button within each row. What I'd like to do is take the value of the data from column index 1 which is in the same row as the button clicked. Confusing? Anyway, here's the code:
public void GetValues(...)
{
//Details regarding connection, querying and inserting table
.
.
.
DataGridViewButtonColumn buttonCol = new DataGridViewButtonColumn();
buttonCol.Name = "ButtonColumn";
buttonCol.HeaderText = "Select";
buttonCol.Text = "Edit";
//NB: the text won't show up on the button. Any help there either?
dataGridView1.Columns.Add(buttonCol);
dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewButtonCell button = (row.Cells["ButtonColumn"] as DataGridViewButtonCell);
}
dataGridView1.Columns["ButtonColumn"].DisplayIndex = 0;
}
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//Here is where I'm having the trouble. What do I put in here???
}
Thanks for any help you can give!
David.
Your DataGridViewCellEventArgs contains very useful information such as RowIndex.
So something like (I don't know what you want to do with the value):
String dataYouWant = dataGridView1.Rows[e.RowIndex].Cells[1].Value;
`
if (e.ColumnIndex != button_column_number) //column number of the button.
return;
dataGridView1.EndEdit();
bool val;
if ((dataGridView1.Rows[e.RowIndex].Cells[1].Value) != null) // column index 1...as that's what you want.
{
//d stuff you want here.
}
else
{
}
`

Categories