Page Top

Winform DataGridView 行单元格增加自定义 ToolTip

啪!贴示例代码

ToolTip _tip = null;

public frmMain()
{
    InitializeComponent();
    InitToolTip();
    InitDgv();
}

private void InitToolTip()
{
    _tip = new ToolTip()
    {
        ReshowDelay = 50,
        AutoPopDelay = 10000,
    };
}

/// <summary>
/// 初始化 dgv
/// </summary>
private void InitDgv()
{
    dgvInfos.Columns.Add(new DataGridViewCheckBoxColumn() { Name = "colIsEnable", DataPropertyName = "IsEnable", HeaderText = "启用", MinimumWidth = 40, Width = 40 });
    dgvInfos.Columns.Add(new DataGridViewTextBoxColumn() { Name = "colServer", DataPropertyName = "Server", HeaderText = "服务器", AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells });
    dgvInfos.Columns.Add(new DataGridViewTextBoxColumn() { Name = "colDb", DataPropertyName = "Db", HeaderText = "数据库", AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells });
    dgvInfos.Columns.Add(new DataGridViewButtonColumn() { Name = "colBtnEdit", HeaderText = "", DefaultCellStyle = new DataGridViewCellStyle() { NullValue = "编辑", Alignment = DataGridViewContentAlignment.MiddleCenter }, MinimumWidth = 60, Width = 60 });

    dgvInfos.MultiSelect = false;
    dgvInfos.RowHeadersVisible = false;
    dgvInfos.ReadOnly = true;
    dgvInfos.AllowUserToResizeRows = false;
    dgvInfos.AllowUserToAddRows = false;
    dgvInfos.AutoGenerateColumns = false;
    dgvInfos.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    dgvInfos.ShowCellErrors = false;
    dgvInfos.ShowCellToolTips = false;
    dgvInfos.ShowEditingIcon = false;
    dgvInfos.ShowRowErrors = false;
}

private void dgvInfos_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0)
    {
        _tip.RemoveAll();
        return;
    }

    try
    {
        string sColName = this.dgvInfos.Columns[e.ColumnIndex].Name;
        var info = ConfigMdl.Settings[e.RowIndex];

        if (sColName == "colServer")
        {
            _tip.ToolTipTitle = "数据库配置";
            _tip.SetToolTip(dgvInfos, string.Format("服务器:{0}\r\n数据库:{1}" info.Server, info.Db));
        }
        else
        {
            _tip.RemoveAll();
        }

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void dgvInfos_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    _tip.RemoveAll();
}

 

posted @ 2021-12-30 12:00  抹茶大虾球丶  阅读(355)  评论(0编辑  收藏  举报