如何在DataGrid中顯示ComboBox
最後更新:2018-12-07
來源:互聯網
上載者:User
//Author:yinzx
//Date:2004-06-08
//Editor:UltraEdit-32
//Ref:www.codeproject.com
//說明:前一段時間要實現如何在DataGrid中顯示ComboBox,在網上找了好多文章,但我的基礎較差,好多看不明白
// 但這種效果實現的原理有兩種:一種是計算ComboBox的位置;另一種不用,而是繼承DataGridTextBoxColumn
// 我最後採用了後一種方式,效果不錯。這裡只是拋磚引玉,要實現更進階的效果,還要加入一特性。
// 如有Bloger對此感興趣,可與我聯絡
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
namespace yinzx
...{
public class GridComboBoxSample:System.Windows.Forms.Form
...{
private DataGrid grd = new DataGrid();
[STAThread]
public static void Main()
...{
Application.Run(new GridComboBoxSample());
}
public GridComboBoxSample()
...{
this.Text = "如何在DataGrid中實現ComboBox";
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.StartPosition = FormStartPosition.CenterScreen;
this.MinimizeBox = this.MaximizeBox = false;
this.Controls.Add(grd);
grd.Dock = DockStyle.Fill;
//產生一個DataTable(表)
DataTable t = new DataTable("PersonInfo");
t.Columns.Add("Name",typeof(string));
t.Columns.Add("Address",typeof(string));
t.Rows.Add(new string[]...{"yinzx","China"});
//產生一個DataGridTableStyle(表樣式)
DataGridTableStyle ts = new DataGridTableStyle();
DataGridTextBoxColumn c1 = new DataGridTextBoxColumn();
DataGridComboBoxColumn c2 = new DataGridComboBoxColumn();
c1.MappingName = c1.HeaderText = "Name";
c2.MappingName = c2.HeaderText = "Address";
c2.FillComboBox(new string[]...{"China","Canada","France"});
ts.MappingName = "PersonInfo";
ts.GridColumnStyles.Add(c1);
ts.GridColumnStyles.Add(c2);
//把表及表樣式綁定到grd上
grd.TableStyles.Add(ts);
grd.DataSource = t;
}
}
public class DataGridComboBoxColumn:DataGridTextBoxColumn
...{
private ComboBox _cbo = new ComboBox();
private CurrencyManager _source;
private int _iRowNum;
public DataGridComboBoxColumn()
...{
_cbo.Leave += new EventHandler(cbo_Leave);
_cbo.Visible = false;
}
public void FillComboBox(string[] cboData)
...{
//填充資料到_cbo中
_cbo.Items.AddRange(cboData);
}
protected override void Edit(CurrencyManager source, int rowNum, Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
...{
if (!this.DataGridTableStyle.DataGrid.Controls.Contains(_cbo)) this.DataGridTableStyle.DataGrid.Controls.Add(_cbo);
_iRowNum = rowNum;
_source = source;
_cbo.Bounds = bounds;//關鍵語句:把_cbo準確定位到相應的儲存格,且不用計算位置
try
...{
_cbo.Text = (string)this.GetColumnValueAtRow(_source, _iRowNum);
}
catch...{}
_cbo.Visible = true;
_cbo.Focus();
}
public void cbo_Leave(object sender, EventArgs e)
...{
try
...{
this.SetColumnValueAtRow(_source,_iRowNum ,_cbo.Text);
}
catch...{}
_cbo.Visible = false;
}
}
}