ฉันใช้ DataGridView เพื่อเติมข้อมูลจากฐานข้อมูล ฉันมีแถว "ประเภท" สองแถว แถวหนึ่งแสดงพาเรนต์ และแถวที่สองแสดงรายการลูก ฉันต้องการให้เด็กๆ เยื้องซ้าย เพื่อจะได้เห็นภาพความสัมพันธ์แบบ "พ่อแม่-ลูก"
สิ่งนี้สามารถทำได้อย่างไร?
ฉันใช้ DataGridView เพื่อเติมข้อมูลจากฐานข้อมูล ฉันมีแถว "ประเภท" สองแถว แถวหนึ่งแสดงพาเรนต์ และแถวที่สองแสดงรายการลูก ฉันต้องการให้เด็กๆ เยื้องซ้าย เพื่อจะได้เห็นภาพความสัมพันธ์แบบ "พ่อแม่-ลูก"
สิ่งนี้สามารถทำได้อย่างไร?
เนื่องจากคุณบอกว่าคุณอาจเน้นแถวลูก ต่อไปนี้เป็นโค้ดบางส่วนที่ต้องทำ คุณยังสามารถเปลี่ยนสีด้านหลังในเหตุการณ์ RowsAdded ได้ แต่วิธีนี้จะเรียบร้อยและเร็วขึ้น (ไม่จำเป็นต้องทาสีแถวสองครั้ง)
จัดการเหตุการณ์ RowPrePaint ของ DataGridView:
private void dataGrid_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
// use whatever your row data type is here
MyDataType item = (MyDataType)(dataGrid.Rows[e.RowIndex].DataBoundItem);
// only highlight children
if (item.parentID != 0)
{
// calculate the bounds of the row
Rectangle rowBounds = new Rectangle(
dataGrid.RowHeadersVisible ? dataGrid.RowHeadersWidth : 0, // left
e.RowBounds.Top, // top
dataGrid.Columns.GetColumnsWidth(DataGridViewElementStates.Visible) - dataGrid.HorizontalScrollingOffset + 1, // width
e.RowBounds.Height // height
);
// if the row is selected, use default highlight color
if (dataGrid.Rows[e.RowIndex].Selected)
{
using (Brush brush = new SolidBrush(dataGrid.DefaultCellStyle.SelectionBackColor))
e.Graphics.FillRectangle(brush, rowBounds);
}
else // otherwise use a special color
e.Graphics.FillRectangle(Brushes.PowderBlue, rowBounds);
// prevent background from being painted by Paint method
e.PaintParts &= ~DataGridViewPaintParts.Background;
}
}
จริงๆ แล้วฉันมักจะชอบใช้แปรงไล่ระดับสีเพื่อเน้นสีแบบพิเศษ:
using (Brush brush = new LinearGradientBrush(rowBounds, color1, color2,
LinearGradientMode.Horizontal))
{
e.Graphics.FillRectangle(brush, rowBounds);
}
โดยที่ color1
และ color2
จะเป็นสีใดก็ตามที่คุณเลือก
Graphics
- person Igby Largeman   schedule 25.08.2011