การเปลี่ยนช่องว่างภายในด้านซ้ายของ DataGridViewRow

ฉันใช้ DataGridView เพื่อเติมข้อมูลจากฐานข้อมูล ฉันมีแถว "ประเภท" สองแถว แถวหนึ่งแสดงพาเรนต์ และแถวที่สองแสดงรายการลูก ฉันต้องการให้เด็กๆ เยื้องซ้าย เพื่อจะได้เห็นภาพความสัมพันธ์แบบ "พ่อแม่-ลูก"

สิ่งนี้สามารถทำได้อย่างไร?


person bobek    schedule 24.08.2011    source แหล่งที่มา
comment
อาจเป็นไปได้โดยการจัดการเหตุการณ์การทาสีเซลล์และแถว คุณจะต้องคุ้นเคยกับการใช้คลาส Graphics   -  person Igby Largeman    schedule 25.08.2011
comment
ใช่ ฉันคิดว่าฉันอาจจะสามารถแยกแยะความแตกต่างระหว่างพ่อแม่และลูกได้อย่างชัดเจน เช่น การนำเสนอสีที่แตกต่างกันอาจเป็นวิธีแก้ปัญหา ฉันหวังว่าจะย้ายแถวเล็กน้อย นั่นจะเป็นการนำเสนอสถาปัตยกรรมที่ดีจริงๆ หากฉันพบวิธีแก้ปัญหาฉันจะโพสต์ไว้ที่นี่   -  person bobek    schedule 25.08.2011
comment
หากคุณตัดสินใจเปลี่ยนสีแถว ฉันสามารถโพสต์และตอบวิธีที่ดีที่สุดในการทำเช่นนั้นได้ แจ้งให้เราทราบหากคุณต้องการมัน   -  person Igby Largeman    schedule 26.08.2011
comment
ฉันอาจจะทำเช่นถ้า parentID != 0 เปลี่ยนสีพื้นหลังเป็นสีเทาและสีตัวอักษรเป็นสีขาวทั้งแถว   -  person bobek    schedule 26.08.2011


คำตอบ (1)


เนื่องจากคุณบอกว่าคุณอาจเน้นแถวลูก ต่อไปนี้เป็นโค้ดบางส่วนที่ต้องทำ คุณยังสามารถเปลี่ยนสีด้านหลังในเหตุการณ์ 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 จะเป็นสีใดก็ตามที่คุณเลือก

person Igby Largeman    schedule 26.08.2011