我正在使用自定义列将数据表绑定到 datagridview。
这是我的自定义列代码。
注意:不涉及单元格编辑。
public class GridCustomColumnCell : DataGridViewColumn
{
public GridCustomColumnCell() : base(new CustomCell())
{
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
// Ensure that the cell used for the template is a CalendarCell.
if (value != null && !value.GetType().IsAssignableFrom(typeof(CustomCell)))
{
throw new InvalidCastException("Must be a Special Cell");
}
base.CellTemplate = value;
}
}
}
public class CustomCell : DataGridViewTextBoxCell
{
private string strID;
private string statusID;
public CustomCell() : base()
{
string[] data = (string[])Value;
if (data != null)
{
strID = data[0];
statusID = data[1];
}
}
private static readonly StringFormat strFmt = new StringFormat(StringFormatFlags.NoWrap);
protected override void Paint(Graphics graphics, Rectangle clipBounds,
Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState,
object value, object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle,
paintParts);
DataGridViewCellStyle cstyle = new DataGridViewCellStyle();
cstyle.Font = new Font(FontFamily.GenericSansSerif, 16, FontStyle.Bold);
graphics.FillRectangle(Brushes.GreenYellow, cellBounds);
graphics.DrawString(" \n\n", cellStyle.Font, Brushes.Black, cellBounds);
graphics.DrawString(" " + statusID + "", cstyle.Font, Brushes.Black,
cellBounds);
graphics.DrawString("\n\n\n " + strID + "", cellStyle.Font,
Brushes.Blue, cellBounds);
}
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
base.OnMouseClick(e);
ContextMenuStrip cs = new ContextMenuStrip();
cs.Items.Add("Fsdfsfs ");
// cs.Items.Add()
if (e.Button == MouseButtons.Right)
cs.Show(Cursor.Position);
}
public override Type ValueType
{
get
{
// Return the type of the value that CalendarCell contains.
return typeof(String[]);
}
}
public override object DefaultNewRowValue
{
get
{
// Use the current date and time as the default value.
return null;
}
}
}
这是我的数据绑定代码:
try
{
FrameFactory ff = new FrameFactory();
ff.NewFrame("C:\\XMLsample\\s1.xml");
GridCustomColumnCell cc = new GridCustomColumnCell();
cc.Resizable = DataGridViewTriState.False;
cc.DataPropertyName = "test";
gridMain.Columns.Add(cc);
gridMain.ReadOnly = true;
this.gridMain.RowCount = 5;
foreach (DataGridViewRow row in this.gridMain.Rows)
{
row.Cells[0].Value = new string[] { "1", "2" };
}
//DataTable dt = new System.Data.DataTable();
//dt.Columns.Add("test", Type.GetType("System.String").MakeArrayType());
//DataRow dr = dt.NewRow();
//dr[0] = new string[] { "1", "2" };
//dt.Rows.Add(dr);
//gridMain.DataSource = dt;
// dt.Row
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
即使使用datatable直接绑定,DataGridViewTextBoxCell下的值为null
任何人都可以帮助我解决丢失的代码吗?