答案 0 :(得分:2)
你可以使用Paint()来完成这项工作。你应该检查网格是否有任何记录,而不是这一行sender.Rows.Count
所以画一个字符串。
private void grd_Paint ( object sender, PaintEventArgs e)
{
DataGridView sender= ( DataGridView )sender;
if ( sender.Rows.Count == 0 )
{
using ( Graphics g= e.Graphics )
{
g.FillRectangle ( Brushes.White, new Rectangle ( new Point (), new Size ( sender.Width, 25 ) ) );
g.DrawString ( "No data to display", new Font ( "Arial", 12 ), Brushes.Red, new PointF ( 3, 3 ) );
}
}
}
答案 1 :(得分:1)
最可重用的方法是继承DataGridView,添加EmptyResultText属性并捕获Paint事件。从那里你可以添加文本到网格的中心,如下所示:
using System.Drawing;
using System.Windows.Forms;
namespace Utility {
public class MyDataGridView : DataGridView {
public string EmptyResultText { get; set; }
public MyDataGridView() {
this.Paint += MyDataGridView_Paint;
}
private void MyDataGridView_Paint(object sender, PaintEventArgs e) {
if (!string.IsNullOrEmpty(EmptyResultText)) {
if (this.Rows.Count == 0) {
using (var gfx = e.Graphics) {
gfx.DrawString(this.EmptyResultText, this.Font, Brushes.Black,
new PointF((this.Width - this.Font.Size * EmptyResultText.Length) / 2, this.Height / 2));
}
}
}
}
}
}
你可以像这样使用它:
var myGrid = new MyDataGridView();
myGrid.EmptyResultText = "No Result Dude";
myGrid.Dock = DockStyle.Fill;
myGrid.DataSource = new List<string>();
groupBox1.Controls.Add(myGrid);