2011-10-08 25 views

Trả lời

19

Xử lý sự kiện CellFormatting của DataGridView và áp dụng một phong cách táo bạo để font nếu ô thuộc về một hàng đã chọn:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    var dataGridView = sender as DataGridView; 
    if (dataGridView.Rows[e.RowIndex].Selected) 
    { 
    e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold); 
    // edit: to change the background color: 
    e.CellStyle.SelectionBackColor = Color.Coral; 
    } 
} 
+0

cảm ơn sự trợ giúp! và làm thế nào để thay đổi BackColor của hàng? – Gali

+0

Chỉ có thể đánh dấu bằng chữ in đậm một số từ trong ô chứ không phải toàn bộ ô? Tôi cần chức năng này để hiển thị nổi bật, nhưng tôi không biết làm thế nào để thực hiện điều này? Có thể ở tất cả? – FrenkyB

+1

@FrenkyB: Xem bài viết [RichTextBox Cell trong một DataGridView] (http://www.codeproject.com/Articles/31823/RichTextBox-Cell-in-a-DataGridView) về dự án mã, nhưng có vẻ như là vấn đề hiệu suất ... Có thể là nếu dữ liệu của bạn chỉ đọc thì có thể chấp nhận được. –

0

Cố gắng xử lý SelectionChanged sự kiện của dữ liệuGridView và đặt kiểu cell.

1

Sau khi tải nội dung trong Datagrid, áp dụng các trình xử lý sự kiện này vào RowEnter và RowLeave.

private void dg_RowEnter(object sender, DataGridViewCellEventArgs e) 
{ 
    System.Windows.Forms.DataGridViewCellStyle boldStyle = new System.Windows.Forms.DataGridViewCellStyle(); 
    boldStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold); 
    dg.Rows[e.RowIndex].DefaultCellStyle = boldStyle; 
} 

private void dg_RowLeave(object sender, DataGridViewCellEventArgs e) 
{ 
    System.Windows.Forms.DataGridViewCellStyle norStyle = new System.Windows.Forms.DataGridViewCellStyle(); 
    norStyle.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular); 
    dg.Rows[e.RowIndex].DefaultCellStyle = norStyle; 
} 

Mã không được kiểm tra. Nhưng nó sẽ hoạt động tốt.

Hy vọng điều đó sẽ hữu ích.

0

Mã dưới đây sẽ làm cho phông chữ dưới phong cách Bold cho hàng đã chọn. "Tổng" là lần kiểm tra hàng cuối cùng trong mã của tôi

protected void gvRow_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
    if (e.Row.Cells[rowIndex].Text == "Total") 
    { 
    e.Row.Font.Bold = true; 
    } 
} 
} 
Các vấn đề liên quan