简体   繁体   中英

C# .NET DataGridView enable cell click only to certain columns

I have little experience in C#.NET, and below is what I got so far:

I created a DataGridView which bound to an ObjectDataSource(a generic list, that is).

Although I can make good use of the DataGridView's CellClick event and its corresponding delegate interface(DataGridViewCellEventHandler) to do my business logic well, I am still not happy with the overall logic.

Basically the drawback of the above approach is that for some certain columns, there's no need to have a CellClick event bound to it. They are simply displaying info, not try to listen to some CellClick events.

I've tried to achieve it for quite some time. I tried to disable such columns from being able to be clicked but got no luck...

Is there a good way go around this issue?

I really don't want to check what's the actual columnIndex in my delegate handler functions and then act accordingly. Basically, if the CellClick wouldn't be triggered in the first place, then that would be an excellent solution.

Many thanks in advance!

@Ian, not entirely true.....If you really don't want to do the filtering, which I don't think is that big a deal to be honest. You can always create your own custom DataGridView and override the OnCellClick event. To make it even simpler you can set the columns you don't want to raise the event for at design time to be and check for that condition before raising the event. 并在引发事件之前检查该条件。

Example:

public class MyDataGridView : DataGridView
{
     public MyDataGridView()
     {
     }

     protected override void OnCellClick(DataGridViewCellEventArgs e)
     {
          if (!Columns[e.ColumnIndex].ReadOnly)
          {
               base.OnCellClick(e);
          }
     }
}

I really don't want to check what's the actual columnIndex in my delegate handler functions and then act accordingly.

Unfortunately you don't have a choice, as the DataGridView does not expose events on its DataGridViewColumn objects. Why is this behavior problematic for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM