程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 如何於DataGridView控件中以跨數據行方式顯示數據

如何於DataGridView控件中以跨數據行方式顯示數據

編輯:.NET實例教程


一般來說,每一個字段的內容會單獨顯示於DataGridVIEw控件的一個數據行中。問題是,某些字段擁有大量文字數據,我是不是能夠讓該字段的內容以跨數據行的方式來顯示,以便在有限的畫面空間中的呈現出更完整的內容呢?答案當然是肯定的。


以圖表1所示的執行畫面而言,「自傳」字段的內容並未單獨顯示於一個數據行中,而是以橫跨數據行的方式,顯示在同筆數據列之各字段內容的下方。相關程序代碼列示如下:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClIEnt;



private int oldRowIndex = 0;
private const int CUSTOM_CONTENT_HEIGHT = 80;
private DataSet myDataSet;

private void CH13_DemoForm009_Load(object sender, EventArgs e)
{
    Padding newPadding = new Padding(0, 1, 0, CUSTOM_CONTENT_HEIGHT);
    this.DataGridVIEw1.RowTemplate.DefaultCellStyle.Padding = newPadding;

    this.DataGridVIEw1.RowTemplate.DefaultCellStyle.SelectionBackColor = 
        Color.Transparent;

    this.DataGridVIEw1.RowTemplate.Height += CUSTOM_CONTENT_HEIGHT;

    this.DataGridVIEw1.AllowUserToAddRows = false;
    this.DataGridView1.EditMode = DataGridVIEwEditMode.EditOnKeystrokeOrF2;
    this.DataGridView1.CellBorderStyle = DataGridVIEwCellBorderStyle.None;
    this.DataGridView1.SelectionMode = DataGridVIEwSelectionMode.FullRowSelect;

    myDataSet = LoadDataToDataSet();

    if(myDataSet != null)
    {
        // 將 BindingSource 組件系結至數據集對象中的「飛狐工作室」數據表。
        this.BindingSource1.DataMember = "飛狐工作室";
        this.BindingSource1.DataSource = myDataSet;

        this.BindingSource1.AllowNew = false;

        // 將 BindingNavigator 控件的數據來源也設定成 BindingSource 組件
        //,如此一來,就可以使用 BindingNavigator 控件去導覽
        // DataGridVIEw 控件中的數據列。
        this.BindingNavigator1.BindingSource = this.BindingSource1;

        this.DataGridVIEw1.DataSource = this.BindingSource1;
    }
    else
    {
        return;
    }

    this.DataGridVIEw1.Columns[4].Visible = false;

    this.DataGridVIEw1.Columns[0].SortMode =
         DataGridVIEwColumnSortMode.NotSortable;
    this.DataGridVIEw1.Columns[2].SortMode =
         DataGridVIEwColumnSortMode.NotSortable;
    this.DataGridVIEw1.Columns[3].SortMode =
         DataGridVIEwColumnSortMode.NotSortable;

 

 


    this.DataGridVIEw1.AutoResizeRows(
        DataGridVIEwAutoSizeRowsMode.AllCellsExceptHeaders);
}

private void DataGridVIEw1_ColumnWidthChanged(object sender,
                                         DataGridVIEwColumnEventArgs e)
{
    this.DataGridVIEw1.Invalidate();
}

private void DataGridVIEw1_CurrentCellChanged(object sender, EventArgs e)
{
    if(oldRowIndex != -1)
    {
        this.DataGridVIEw1.InvalidateRow(oldRowIndex);
    }

    oldRowIndex = this.DataGridVIEw1.CurrentCellAddress.Y;
}

private void DataGridVIEw1_RowPrePaint(object sender,
                            DataGridVIEwRowPrePaintEventArgs e)
{
    e.PaintParts = e.PaintParts & (~DataGridVIEwPaintParts.Focus);

    if((e.State & DataGridVIEwElementStates.Selected) ==
                                DataGridVIEwElementStates.Selected)
    {
        Rectangle rowBounds = new Rectangle(
            this.DataGridVIEw1.RowHeadersWidth, e.RowBounds.Top, 
            this.DataGridVIEw1.Columns.GetColumnsWidth(
            DataGridVIEwElementStates.Visible) - 
            this.DataGridVIEw1.HorizontalScrollingOffset + 1, 
            e.RowBounds.Height);

        System.Drawing.Drawing2D.LinearGradIEntBrush backbrush = 
            new System.Drawing.Drawing2D.LinearGradIEntBrush(rowBounds, 
            this.DataGridVIEw1.DefaultCellStyle.SelectionBackColor, 
            e.InheritedRowStyle.ForeColor, 
            System.Drawing.Drawing2D.LinearGradIEntMode.Horizontal);

 &n
bsp;      try
        {
            e.Graphics.FillRectangle(backbrush, rowBounds);
        }
        finally
        {
            backbrush.Dispose();
        }
    }
}

private void DataGridVIEw1_RowPostPaint(object sender,
                               DataGridVIEwRowPostPaintEventArgs e)
{
    Rectangle rowBounds = new Rectangle(this.DataGridVIEw1.RowHeadersWidth, 
        e.RowBounds.Top, this.DataGridVIEw1.Columns.GetColumnsWidth(
    
    DataGridVIEwElementStates.Visible) - 
        this.DataGridVIEw1.HorizontalScrollingOffset + 1, e.RowBounds.Height);

    SolidBrush forebrush = null;

    try
    {
        if((e.State & DataGridVIEwElementStates.Selected) ==
            DataGridVIEwElementStates.Selected)
        {
            forebrush = new SolidBrush(e.InheritedRowStyle.SelectionForeColor);
        }
        else
        {
            forebrush = new SolidBrush(e.InheritedRowStyle.ForeColor);
        }

        Object recipe =
          this.DataGridVIEw1.Rows.SharedRow(e.RowIndex).Cells[4].Value;

        if(!(recipe == null))
        {
            string text = recipe.ToString();
            Rectangle textArea = rowBounds;
            RectangleF clip = textArea;

            textArea.X -= this.DataGridVIEw1.HorizontalScrollingOffset;
            textArea.Width += this.DataGridVIEw1.HorizontalScrollingOffset;
            textAr
ea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom;
            textArea.Height -= rowBounds.Height -
                                   e.InheritedRowStyle.Padding.Bottom;
            textArea.Height =
               (textArea.Height / e.InheritedRowStyle.Font.Height) * 
                e.InheritedRowStyle.Font.Height;
            
            clip.Width -= this.DataGridVIEw1.RowHeadersWidth + 1 - clip.X;
            clip.X = this.DataGridVIEw1.RowHeadersWidth + 1;
                   
            RectangleF oldClip = e.Graphics.ClipBounds;

            e.Graphics.SetClip(clip);

            e.Graphics.DrawString(text, e.InheritedRowStyle.Font,
                                  forebrush, textArea);

            e.Graphics.SetClip(oldClip);
        }
    }
    finally
    {
        forebrush.Dispose();
    }

    if (this.DataGridVIEw1.CurrentCellAddress.Y == e.RowIndex)
    {
        e.DrawFocus(rowBounds, true);
    }
}

private void DataGridVIEw1_RowHeightChanged(
                    object sender, DataGridVIEwRowEventArgs e)
{
    int preferredNormalContentHeight = 
       e.Row.GetPreferredHeight(e.Row.Index, 
        DataGridVIEwAutoSizeRowMode.AllCellsExceptHeader, true) - 
        e.Row.DefaultCellStyle.Padding.Bottom;

    Padding newPadding = e.Row.DefaultCellStyle.Padding;
         &nbs
p;  
    newPadding.Bottom = e.Row.Height - preferredNormalContentHeight;
    e.Row.DefaultCellStyle.Padding = newPadding;
}

// 本程序會連接至數據來源並建立所需的 DataSet 對象。
private DataSet LoadDataToDataSet()
{
    // 利用 SqlConnectionStringBuilder 對象來構建連接字符串。
    SqlConnectionStringBuilder sqlStringBuilder = 
        new SqlConnectionStringBuilder();

    sqlStringBuilder.DataSource = @"(local)\SQLEXPRESS";
    sqlStringBuilder.InitialCatalog = "北風貿易";
    sqlStringBuilder.IntegratedSecurity = true;

    // 建立一個數據集。
    DataSet ds = new DataSet();

    try
    {
        using (SqlConnection northwindConnection =
            new SqlConnection(sqlStringBuilder.ConnectionString))
        {
            SqlCommand cmdLiming = new SqlCommand(
              "SELECT 姓名,員工性別,出生日期, 目前薪資, 自傳" +
              " FROM dbo.飛狐工作室 WHERE 自傳 IS NOT NULL",
              northwindConnection);

            northwindConnection.Open();

            using (SqlDataReader drLiming = cmdLiming.ExecuteReader())
            {
                ds.Load(
                  drLiming,
                  LoadOption.OverwriteChanges,
                  new string[] { "飛狐工作室" });
            }
        }
    }
    catch (Exception)
    {
        MessageBox.Show(
            "要能夠順利執行本范例程序,您的計算機必須已安裝 SQL Server " +
            "Express,並且必須已附加了本書所附的「北風貿易」數據庫。" +
            "關於如何安裝 SQL Server Express,請參閱附錄或相關文件說明。");

        // 無法連接至 SQL Ser
ver。
        return null;
    }

    return ds;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved