在DataGridView中设置所有列运行时的默认值 [英] Set default value of all columns runtime in DataGridView
问题描述
我在datagridview上添加了n个列数。列数不固定,列名也固定。我也想为每行中的所有列添加deault值,例如
I am adding n Numbers of columns on a datagridview. The number of columns is not fixed and also the name of column is fixed. Also i want to add deault value for all columns in every rows like
这些列也在运行时添加,并且gird的数据源也与类相关联
Also these columns are added on runtime and datasource of gird is also associate with a class
DbDataEntities db = new DbDataEntities();
var MasterAttendanceTypesDetail = db.MasterAttendanceTypes.ToList();
foreach (string AttendanceType in MasterAttendanceTypesDetail.Select(s => s.AttendanceTypeName).ToList())
{
if (!dgv1.Columns.Contains(AttendanceType))
{
DataGridViewColumn dgchkCol = new DataGridViewColumn();
dgchkCol.Name = AttendanceType;
dgv1.Columns.Add(dgchkCol);
}
}
网格中添加的列数取决于表格中的条目几乎是100。
因此如何设置每列的默认值。
Number of columns added in grid is depend on number of entries in tabel at it is almost 100.
thus how could i set default value of each column.
推荐答案
您可以继承DataGridViewColumn和DataGridViewCell并覆盖 DefaultNewRowValue 属性。
You can inherit the DataGridViewColumn and DataGridViewCell and override the DefaultNewRowValue property.
public class ExtendedColumn : DataGridViewColumn
{
public ExtendedColumn()
: base(new ExtendedCell())
{
}
}
public class ExtendedCell : DataGridViewTextBoxCell
{
public ExtendedCell()
: base()
{
}
public override object DefaultNewRowValue
{
get
{
return "aaa";
}
}
}
并在您的代码中使用像这样:
And use it in your code like this:
ExtendedColumn col = new ExtendedColumn();
col.Name = AttendanceType;
dgv1.Columns.Add(col);
此处是指向MSDN的链接,该链接演示了DefaultNewRowValue的使用:
Here is a link to MSDN that demonstrates the use of DefaultNewRowValue:
但是由于您可以有许多需要默认值的列,因此您可以处理 DefaultValuesNeeded 事件。
But since you can have many columns for which default value is required, you can handle DefaultValuesNeeded event.
dataGridView1.DefaultValuesNeeded +=new DataGridViewRowEventHandler(dataGridView1_DefaultValuesNeeded);
private void dataGridView1_DefaultValuesNeeded(object sender,
System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells[0].Value = "aaa";
e.Row.Cells[1].Value = "bbb";
e.Row.Cells[2].Value = "ccc";
}
这篇关于在DataGridView中设置所有列运行时的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!