如何在Windows应用程序中为DataGridView创建EmptyDataText

imd*_*sen 5 datagridview custom-controls winforms

今天我面临着根据数据源显示/隐藏标签的问题.如果数据源没有行,那么我想设置"No Data Found",否则显示winforms应用程序中的记录数.

这可以在Asp.net中像:

<emptydatatemplate>
No Data Found
</emptydatatemplate>
Run Code Online (Sandbox Code Playgroud)

要么

EmptyDataText=" No Data Found"
Run Code Online (Sandbox Code Playgroud)

但我想在Windows应用程序中.如果您有相同的解决方案,请帮助我.

任何解决方案将不胜感激!谢谢,Imdadhusen

imd*_*sen 12

您可以实现此目的的一种方法是使用Paint()事件来检查行,如果没有,则写下您的消息:Collapse

private void dataGridView1_Paint ( object sender, PaintEventArgs e )
{
    DataGridView sndr = ( DataGridView )sender;

    if ( sndr.Rows.Count == 0 ) // <-- if there are no rows in the DataGridView when it paints, then it will create your message
    {
        using ( Graphics grfx = e.Graphics )
        {
            // create a white rectangle so text will be easily readable
            grfx.FillRectangle ( Brushes.White, new Rectangle ( new Point (), new Size ( sndr.Width, 25 ) ) );
            // write text on top of the white rectangle just created
            grfx.DrawString ( "No data returned", new Font ( "Arial", 12 ), Brushes.Black, new PointF ( 3, 3 ) );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢JOAT-MON提供的解决方案.

谢谢,Imdadhusen