Why are you adding an event handler every time you drop an item?
Wouldn't it make more sense to have just the single one handler, particularly since you are putting them all to the same handler method.
Instead, set up the handler once, in form load, or at design time, and try setting the row and column first:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Point p = this.dataGridView1.PointToClient(new Point(e.X, e.Y));
DataGridView.HitTestInfo info = this.dataGridView1.HitTest(p.X, p.Y);
if (info.RowIndex != -1 && info.ColumnIndex != -1)
{
Object value = (Object)e.Data.GetData(typeof(string));
x = info.RowIndex;
y = info.ColumnIndex;
this.dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex].Value = value;
}
}
"i drag Courses from the listbox into timetable(datagridview). when i did it like u worte, still the previous cellpainting event in datagridview disappears and only last event appears."
Which is exactly what I would expect - that is what you have asked it to do.
If you want to preserve previous cells as well, you need to replace your "x" and "y" with a list (or other collection) to hold the ones you want to highlight:
private List<Point> makeRed = new List<Point>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
Point p = this.dataGridView1.PointToClient(new Point(e.X, e.Y));
DataGridView.HitTestInfo info = this.dataGridView1.HitTest(p.X, p.Y);
if (info.RowIndex != -1 && info.ColumnIndex != -1)
{
Object value = (Object)e.Data.GetData(typeof(string));
makeRed.Add(new Point(e.RowIndex, e.ColumnIndex));
this.dataGridView1.Rows[info.RowIndex].Cells[info.ColumnIndex].Value = value;
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (makeRed.Contains(new Point(e.RowIndex, e.ColumnIndex)))
{
e.Graphics.FillRectangle(Brushes.Red, e.CellBounds);
e.PaintContent(e.CellBounds);
e.Handled = true;
}
}