Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys,

I am finding it quite difficult to get a rowindex of a current selected cell of a datagrid in WPF 4.0? I don't want at all value or item of current cell.

If any body has clear idea please do reply.
Thanks

I am really confused,Is really WPF rich in terms of data handling with respect to its brother hood windows form's controls?
It seems to be headache for finding simple properties/facility in WPF datagrid which are provided by datagridview in windows form.

Seems to be in building process of better controls(not by looks)
The way of coding is changed 70 percent while migrating to WPF from windows forms.:confused:
Posted
Updated 6-Dec-10 2:10am
v3
Comments
Tarun.K.S 6-Dec-10 8:22am    
The datagridview of windows form is much better than the datagrid of WPF.

Try this out[^].
 
Share this answer
 
// Declare the delegate globally
public delegate Point GetDragDropPosition(IInputElement theElement);
int prevRowIndex = -1;

We can get it from datagrid preview mouse left button down event.
Declare it at the constructor level

public MainWindow()
{
InitializeComponent();
this.dgEmployee.PreviewMouseLeftButtonDown+=new MouseButtonEventHandler(dgEmployee_PreviewMouseLeftButtonDown);
}



private void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition);

if (prevRowIndex < 0)
return;

dgEmployee.SelectedIndex = prevRowIndex;

}

Method to get the current row index
private int GetDataGridItemCurrentRowIndex(GetDragDropPosition pos)
{
int currIndex = -1;
for (int i = 0; i < dgEmployee.Items.Count; i++)
{
DataGridRow item = GetDataGridRowItem(i);
if(IsTheMouseOnTargetRow(item,pos))
{
currIndex=i;
break;
}
}
return currIndex;
}


Just try this out..!!
private bool IsTheMouseOnTargetRow(Visual theTarget, GetDragDropPosition pos)
{
Rect posBounds = VisualTreeHelper.GetDescendantBounds(theTarget);
Point theMousePos = pos((IInputElement)theTarget);
return posBounds.Contains(theMousePos);
}

private DataGridRow GetDataGridRowItem(int index)
{
if (dgEmployee.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
return null;
return dgEmployee.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900