winform datagridview 刷新数据不需要重新绑定以及添加COMBOX方法
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DatagridviewTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; BindCombox(); BindDatasources(); } int vscroll = 0, hscroll = 0; #region datagridview 绑定数据自动刷新、添加、删除等 /// <summary> /// datagridview 数据源 /// 必须使用BindingList, 如果使用LIST,无法实现更改,添加、删除数据源自动更新datagridview /// </summary> BindingList<Studect> studentLst = new BindingList<Studect>(); void BindDatasources() { studentLst.Add(new Studect() { Name = "A", Age = 10, UpdateTime = DateTime.Now.ToString(), Sex = 1 }); studentLst.Add(new Studect() { Name = "B", Age = 10, UpdateTime = DateTime.Now.ToString(), Sex = 1 }); studentLst.Add(new Studect() { Name = "C", Age = 10, UpdateTime = DateTime.Now.ToString(), Sex = 1 }); studentLst.Add(new Studect() { Name = "D", Age = 10, UpdateTime = DateTime.Now.ToString(), Sex = 1 }); studentLst.Add(new Studect() { Name = "E", Age = 10, UpdateTime = DateTime.Now.ToString(), Sex = 0 }); this.dataGridView1.DataSource = studentLst; dataGridView1.FirstDisplayedScrollingRowIndex = vscroll; dataGridView1.HorizontalScrollingOffset = hscroll; } private void button1_Click(object sender, EventArgs e) { studentLst.Add(new Studect() { Name = DateTime.Now.ToString(), Age = 10, UpdateTime = DateTime.Now.ToString() }); } private void button2_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows != null) { Studect s = dataGridView1.CurrentRow.DataBoundItem as Studect; if (s != null) studentLst.Remove(s); } } #endregion #region datagridview 添加combox下拉框 ComboBox sexCmb = new ComboBox(); private void BindCombox() { List<ContainerType<int>> SexLst = new List<ContainerType<int>>() { new ContainerType<int>(){ Value = 0,Describle="男"}, new ContainerType<int>(){ Value = 1,Describle="女"}, }; #region 方法一 //sexCmb.DisplayMember = "Describle"; //sexCmb.ValueMember = "Value"; //sexCmb.DataSource = SexLst; //sexCmb.DropDownStyle = ComboBoxStyle.DropDownList; //sexCmb.DrawMode = DrawMode.OwnerDrawFixed; //sexCmb.DrawItem += SexCmb_DrawItem; //// 设置下拉列表框不可见 //sexCmb.Visible = false; //// 添加下拉列表框事件 //sexCmb.SelectedIndexChanged += new EventHandler(cmb_Temp_SelectedIndexChanged); //dataGridView1.Scroll += dataGridView1_Scroll; //dataGridView1.ColumnWidthChanged += dataGridView1_ColumnWidthChanged; //dataGridView1.CurrentCellChanged += dataGridView1_CurrentCellChanged; ////dataGridView1.DataBindingComplete += DataGridView1_DataBindingComplete; //// 将下拉列表框加入到DataGridView控件中 //this.dataGridView1.Controls.Add(sexCmb); #endregion #region 方法二 DataGridViewTextBoxColumn c1 = new DataGridViewTextBoxColumn(); c1.DataPropertyName = "Name"; c1.HeaderText = "名字"; dataGridView1.Columns.Add(c1); DataGridViewComboBoxColumn dgvCmb = new DataGridViewComboBoxColumn(); dgvCmb.DisplayMember = "Describle"; dgvCmb.ValueMember = "Value"; dgvCmb.DataSource = SexLst; dgvCmb.DataPropertyName = "Sex"; dgvCmb.HeaderText = "性别"; //dgvCmb.FlatStyle = FlatStyle.Flat; dgvCmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; //dgvCmb. dataGridView1.Columns.Add(dgvCmb); //dataGridView1.CellEnter += DataGridView1_CellEnter; dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing; dataGridView1.CellEndEdit += DataGridView1_CellEndEdit; //dataGridView1.e #endregion } private void DataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { //实现单击一次显示下拉列表框 if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1) { SendKeys.SendWait("{F4}"); } } private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (sexCmb != null) { sexCmb.DrawItem -= Cmb_DrawItem; //sexCmb.Dispose(); sexCmb = null; } } private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl)) { sexCmb = e.Control as ComboBox; sexCmb.DrawMode = DrawMode.OwnerDrawFixed; sexCmb.DrawItem += Cmb_DrawItem; } } private void Cmb_DrawItem(object sender, DrawItemEventArgs e) { ComboBox combox = sender as ComboBox; Pen fColor = new Pen(Color.Black); Pen bColor = new Pen(Color.White); var a = combox.Items[e.Index] as ContainerType<int>; if (a.Value == 0) { fColor = new Pen(Color.Green); } else { fColor = new Pen(Color.Red); } if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { bColor = new Pen(Color.Blue); fColor = new Pen(Color.White); } e.Graphics.FillRectangle(bColor.Brush, e.Bounds); e.Graphics.DrawString(a.Describle, this.Font, fColor.Brush, e.Bounds); //combox.DrawItem -= Cmb_DrawItem; } private void Combox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox combox = sender as ComboBox; combox.SelectedIndexChanged -= Combox_SelectedIndexChanged; } private void SexCmb_DrawItem(object sender, DrawItemEventArgs e) { //初始化字体和背景色 Pen fColor = new Pen(Color.Black); Pen bColor = new Pen(Color.White); //if (e.Index < 0) return; var a = sexCmb.Items[e.Index] as ContainerType<int>; if (a.Value == 0) { fColor = new Pen(Color.Green); } else { fColor = new Pen(Color.Red); } e.Graphics.FillRectangle(bColor.Brush, e.Bounds); e.Graphics.DrawString(a.Describle, this.Font, fColor.Brush, e.Bounds); } private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { for (int i = 0; i < this.dataGridView1.Rows.Count; i++) { //for (int c = 0; c < dataGridView1.Columns.Count; c++) //{ //} if (dataGridView1.Rows[i].Cells[2].Value != null) { if (dataGridView1.Rows[i].Cells[2].Value.ToString().Trim() == "1") { dataGridView1.Rows[i].Cells[2].Value = "女"; } else if(dataGridView1.Rows[i].Cells[2].Value.ToString().Trim() == "0") { dataGridView1.Rows[i].Cells[2].Value = "男"; } } } } // 当用户移动到性别这一列时单元格显示下拉列表框 private void dataGridView1_CurrentCellChanged(object sender, EventArgs e) { DataGridViewCell CurrnetCell = dataGridView1.CurrentCell; if (CurrnetCell != null && CurrnetCell.OwningColumn.HeaderText == "性别") { Rectangle TmpRect = dataGridView1.GetCellDisplayRectangle(CurrnetCell.ColumnIndex, CurrnetCell.RowIndex, false); sexCmb.SelectedValue = CurrnetCell.Value; //sexCmb.Text = CurrnetCell.Value.ToString(); sexCmb.Size = TmpRect.Size; sexCmb.Top = TmpRect.Top; sexCmb.Left = TmpRect.Left; sexCmb.Visible = true; } else { sexCmb.Visible = false; } } // 滚动DataGridView时将下拉列表框设为不可见 private void dataGridView1_Scroll(object sender, ScrollEventArgs e) { if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll) { hscroll = e.NewValue; } else if (e.ScrollOrientation == ScrollOrientation.VerticalScroll) { vscroll = e.NewValue; } this.sexCmb.Visible = false; } // 改变DataGridView列宽时将下拉列表框设为不可见 private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e) { this.sexCmb.Visible = false; } private void button3_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows != null) { Studect s = dataGridView1.CurrentRow.DataBoundItem as Studect; if (s != null) { s.Name = DateTime.Now.ToString();//修改名称,界面自动更新 } } } // 当用户选择下拉列表框时改变DataGridView单元格的内容 private void cmb_Temp_SelectedIndexChanged(object sender, EventArgs e) { dataGridView1.CurrentCell.Value = ((ComboBox)sender).SelectedValue; } //sexComb #endregion } /// <summary> /// /// </summary> public class Studect : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); } string _name; [DisplayName("你的名字")] // 这是显示的列名称哦 public string Name { get { return _name; } set { if (_name != value) { _name = value; NotifyPropertyChanged("Name"); } } } // 2) 在属性改变时引发事件 int _age; [DisplayName("他的年纪")] public int Age { get { return _age; } set { if (_age != value) { _age = value; } } } int _sex; [DisplayName("性别")] public int Sex { get { return _sex; } set { _sex = value; } } //List<ContainerType<int>> _sexlst; //[DisplayName("性别")] //public List<ContainerType<int>> SexLst //{ // get { return _sexlst; } // set { _sexlst = value; } //} string _updateTime; [DisplayName("更新时间")] public string UpdateTime { get { return _updateTime; } set { if (_updateTime != value) { _updateTime = value; } } } } public class ContainerType<T> { public T Value { get; set; } public string Describle { get; set; } } }