Highlighting entire row when cell is clicked in datagrid

C

Charlie@CBFC

Hi:

Using the WinForms DataGrid, I would like to have the entire row highlight
rather than just the cell that was last clicked. How do you do this?

Thanks,
Charlie
 
P

Patrick B

Charlie,

I wanted something like this too. I created a new control called a
DataBrowser -- just like a DataGrid but with a few changes...

public class DataBrowser : System.Windows.Forms.DataGrid
{
}

I wanted it to work like a multi-column listbox: you click on a cell and
the whole row gets highlighted. I also wanted to prevent columns from
being resized.

I used the following function to get that behavior:

protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
DataGrid.HitTestInfo hitTestInfo = this.HitTest(e.X, e.Y);
if (hitTestInfo.Type == HitTestType.ColumnResize
|| hitTestInfo.Type == HitTestType.RowResize) {
return;
}
base.OnMouseDown(e);
if ( hitTestInfo.Type == HitTestType.Cell) {
SelectRow(hitTestInfo.Row);
}
return;
}

That function reacts to the mouse click and calls my other function,
SelectRow, which in turn calls HighlightRow...

public void SelectRow(int index)
{
HighlightRow(index);
this.CurrentRowIndex = index;
return;
}
int highlightedRow = -1; // we use -1 to mean no selection
private void HighlightRow(int index)
{
CurrencyManager currencyManager;
currencyManager = (CurrencyManager) this.BindingContext[this.DataSource];
int rowCount = currencyManager.Count;
if (index < 0 || index > rowCount - 1)
return;
if (highlightedRow > -1 && highlightedRow < rowCount)
this.UnSelect(highlightedRow);
this.Select(index);
highlightedRow = index;
return;
}

Finally, one more function:

protected override void OnCurrentCellChanged(System.EventArgs e)
{
HighlightRow(this.CurrentCell.RowNumber);
base.OnCurrentCellChanged(e);
return;
}

That got it working for me. Put it all in a class and use the new
control in the designer.

I'm sure the code could use refinement. One problem is that if you use
the keyboard to navigate past the top or bottom of the list, you can
make the highlight disappear even though a record is selected. If you
improve it, share back.

-Patrick
 
G

Guest

Hi:
I made the same thing (I think) only by doing this:
private void dataGrid1_Click(object sender, System.EventArgs e)
{
dataGrid1.Select(dataGrid1.CurrentRowIndex);
}
I also associated the CurrentCellChanged Event with the same function.

Best Regards

Emo Markov
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top