如何在运行时更改DataGridViewComboBoxColumn
的以下内容:
原因:
我这样做的原因是因为Enum
我有Status{New=1,Stop=2,Temp=3}
。当我想注册学生时,状态始终设置为New
。因此,当我保存时,它会自动保存Status = 1
。
答案 0 :(得分:9)
以下是设置默认值并禁用单元格的方法:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Column1.DataSource = new int[] { 1, 2, 3 };
Column1.DataPropertyName = "Number";
dataGridView1.DataSource = new[]
{
new { Number=1 },
new { Number=2 },
new { Number=3 },
new { Number=1 }
};
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == Column1.Index && e.RowIndex == (dataGridView1.Rows.Count - 1))
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];
cell.Value = 2;
cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
cell.ReadOnly = true;
}
}
}
}
答案 1 :(得分:0)
根据这些文章,DataGridView组合框控件有SelectedIndex:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing.aspx
[1]。我就是这样做的:
private void dgv_EditingControlShowing(object sender, System.Windows.Forms.DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewComboBoxEditingControl) {
DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;
BindingSource bs = control.DataSource as BindingSource;
if (!IsNothing(bs)) {
// set the filteredChildBS as the DataSource of the editing control
((ComboBox)e.Control).DataSource = filteredChildBS;
//Set the dgv's combobox to the first item
((ComboBox)e.Control).SelectedIndex = 1
}
}
}
filtereredChildBS是一个绑定源,如果您需要澄清,请告诉我?
[2]。禁用datagridview控制它有点棘手。我使用此示例禁用DataGridView复选框:http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/988c7e3f-c172-467d-89b7-b80a60b7f24f/但对于组合框,更简单的方法是禁用列带:
foreach (DataGridViewBand band in dgvTransactions.Columns) { if (i !=7) band.ReadOnly = (bool)i == 0; i+= 1; band.Frozen = false; }
如果您需要进一步澄清,请告诉我?