Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Expert,

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:
XML
<emptydatatemplate>
   No Data Found
</emptydatatemplate>

OR
XML
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
Posted

1 solution

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:
C#
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 ) );
        }
    }
}
 
Share this answer
 
Comments
Sunasara Imdadhusen 4-May-11 1:08am    
Excellent job!!!
Thanks a lot.
My vote of 5
JOAT-MON 4-May-11 18:02pm    
You're very welcome. I'm glad it was useful for you. Thank you for the vote. :)
Sunasara Imdadhusen 5-May-11 1:14am    
Is this possible to overwrite Paint method (like creating component class)
public class DataGrid : DataGridView
{
protected override void OnPaint(PaintEventArgs e)
{
//Code goes here...
}
}
Otherwise i have to set this event for entire project grids.

Again thanks.
JOAT-MON 5-May-11 1:20am    
Yep, that should work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900