How to creating EmptyDataText for DataGridView in Windows Application

时光毁灭记忆、已成空白 提交于 2019-12-17 19:45:17

问题


Today i am facing problem to show/hide label according to data source. If the data source has no row then i would like to set "No Data Found" else display number of records in winforms application.

This would be possible in Asp.net like:

<emptydatatemplate>
No Data Found
</emptydatatemplate>

OR

EmptyDataText=" No Data Found"

But I would like in Windows Application. Please help me if you have any solution for the same.

Any solution would be appreciated! Thanks, Imdadhusen


回答1:


One way you could accomplish this is to use the Paint() event to check the rows and if there are none, then write your message: 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 ) );
        }
    }
}

Thanks JOAT-MON for accepted solution.

Thanks, Imdadhusen




回答2:


Since I'm having troubles implementing this behavior using the Paint event, I solved by adding a panel to my form containing the graphics I want to show when no data is displayed (basically a couple of labels) and swap it with the grid when needed.



来源:https://stackoverflow.com/questions/5866458/how-to-creating-emptydatatext-for-datagridview-in-windows-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!