日期:2014-05-18  浏览次数:20955 次

winForm中,如何在datagrid中动态生成一列按钮列? (2003版本)
如题

据说需要重载DataGridColumnStyle
哪位大虾可以帮忙给个代码示例?
谢谢

另:
我用的C# VB看不懂 谢谢

------解决方案--------------------
在网上帮你找了一个,可以参照一下
C# code
	public class DataGridButtonColumn : DataGridTextBoxColumn 
{
public event DataGridCellButtonClickEventHandler CellButtonClicked;

private Bitmap _button;
private Bitmap _buttonPressed;
private int _columnNum;
private int _pressedRow;

public DataGridButtonColumn(int colNum)
{
_columnNum = colNum;
_pressedRow = -1;

//you will need to change the Assembly name in GetManifestResourceStream()
try
{
char[] c={','};
System.IO.Stream strm = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.ToString().Split(c,10)[0]+".button.bmp");
_button = new Bitmap(strm);
strm = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.ToString().Split(c,10)[0]+".buttonpressed.bmp");
_buttonPressed = new Bitmap(strm);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

}

protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
// dont call the baseclass so no editing done...
// base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}

private void DrawButton(Graphics g, Bitmap bm, Rectangle bounds, int row)
{

DataGrid dg = this.DataGridTableStyle.DataGrid;
string s = dg[row, this._columnNum].ToString();

SizeF sz = g.MeasureString(s, dg.Font, bounds.Width - 4, StringFormat.GenericTypographic);

int x = bounds.Left + Math.Max(0, (bounds.Width - (int)sz.Width)/2);
g.DrawImage(bm, bounds, 0, 0, bm.Width, bm.Height,GraphicsUnit.Pixel);

if(sz.Height < bounds.Height)
{
int y = bounds.Top + (bounds.Height - (int) sz.Height) / 2;
if(_buttonPressed == bm)
{
x++;
}

g.DrawString(s, dg.Font, new SolidBrush(dg.ForeColor), x, y);
}

}

public void HandleMouseUp(object sender, MouseEventArgs e)
{
DataGrid dg = this.DataGridTableStyle.DataGrid;
DataGrid.HitTestInfo hti = dg.HitTest(new Point(e.X, e.Y));
bool isClickInCell = (hti.Column == this._columnNum
&& hti.Row > -1);

_pressedRow = -1;

Rectangle rect = new Rectangle(0,0,0,0);

if(isClickInCell)
{
rect = dg.GetCellBounds(hti.Row, hti.Column);
isClickInCell = (e.X > rect.Right - this._button.Width);
}
if(isClickInCell)
{
Graphics g = Graphics.FromHwnd(dg.Handle);
// g.DrawImage(this._button, rect.Right - this._button.Width, rect.Y);
DrawButton(g, this._button, rect, hti.Row);
g.Dispose();
if(CellButtonClicked != null)
CellButtonClicked(this, new DataGridCellButtonClickEventArgs(hti.Row, hti.Column));
}
}

public void HandleMouseDown(object sender, MouseEventArgs e)
{
DataGrid dg = this.DataGridTableStyle.DataGrid;
DataGrid.HitTestInfo hti = dg.HitTest(new Point(e.X, e.Y));
bool isClickInCell = (hti.Column == this._columnNum
&& hti.Row > -1);

Rectangle rect = new Rectangle(0,0,0,0);
if(isClickInCell)
{