Bud*_*Joe 19 .net data-binding datagridview winforms
我将List绑定到DataGridView.SomeObject类的一个属性是状态代码(例如Red,Yellow,Green).我可以轻松地将状态"绑定"到单元格的背景颜色吗?如何绑定到工具提示呢?
Dav*_* R. 35
您可以为DataGridView的CellFormatting事件编写处理程序以自定义背景颜色.这是一个有用的示例(您需要将DataGridView拖到默认窗体上,然后双击CellFormatting事件以创建处理程序):
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private BindingSource _source = new BindingSource();
public Form1()
{
InitializeComponent();
_source.Add(new MyData(Status.Amber, "Item A"));
_source.Add(new MyData(Status.Red, "Item B"));
_source.Add(new MyData(Status.Green, "Item C"));
_source.Add(new MyData(Status.Green, "Item D"));
dataGridView1.DataSource = _source;
dataGridView1.Columns[0].Visible = false;
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1)
{
DataGridView dgv = sender as DataGridView;
MyData data = dgv.Rows[e.RowIndex].DataBoundItem as MyData;
switch (data.Status)
{
case Status.Green:
e.CellStyle.BackColor = Color.Green;
break;
case Status.Amber:
e.CellStyle.BackColor = Color.Orange;
break;
case Status.Red:
e.CellStyle.BackColor = Color.Red;
break;
}
}
}
}
public class MyData
{
public Status Status { get; set; }
public string Text { get; set; }
public MyData(Status status, string text)
{
Status = status;
Text = text;
}
}
public enum Status
{
Green,
Amber,
Red
}
}
Run Code Online (Sandbox Code Playgroud)
为简单起见,这里的对象只有状态和文本.我为这些对象的一组示例创建了一个BindingSource,然后将其用作DataGridView的数据源.默认情况下,网格会在您绑定时自动生成列,因此无需手动执行此操作.我还隐藏了第一列,它绑定到Status值,因为我们将改为为Text单元着色.
为了实际绘画,我们回应CellFormatting事件.我们通过转换发送者来获取对DataGridView的引用,然后使用DataGridViewCellFormattingEventArgs对象的RowIndex属性来获取数据项iteself(每个Row都有一个DataBoundItem属性,方便地给我们这个).由于DataBoundItem是一个对象类型,我们需要将它转换为我们的特定类型,然后我们实际上可以到达Status属性本身...... p!
我没有任何工具提示编程经验,但我认为你应该响应MouseHover事件,然后继续发现指向哪一行.
我希望这有帮助.
归档时间: |
|
查看次数: |
13230 次 |
最近记录: |