在我的项目中,我将ComboBox,Text,Link标签添加到我的DataGridView dgvMain
。我为不同的单元格模板创建了不同的方法,如下所示:(以下代码正在工作)
gridLnklbl(string headerName)
DataGridViewLinkColumn col = new DataGridViewLinkColumn();
col.HeaderText = headerName; //
col.Name = "col" + headerName; // same code repeating to all the methods
dgvMain.Columns.Add(col); //
gridCmb(string headerName)
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.HeaderText = headerName;
col.Name = "col" + headerName;
dgvMain.Columns.Add(col);
gridText(string headerName)
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
col.HeaderText = headerName;
col.Name = "col" + headerName;
dgvMain.Columns.Add(col);
正如您所看到的,除了对象声明之外,每个方法的代码都在重复。只是好奇地知道,重复代码可以转换为单一方法吗?我不知道该怎么做..它不是3行代码,我写了更多的行,这些可以使这些方法通用。
答案 0 :(得分:1)
所有列类型都派生自DataGridViewColumn,其中包含HeaderText和Name属性。您可以创建一个采用此基本类型的方法,并设置值:
public void AddColumnHeader(DataGridViewColumn column, string headerName)
{
column.HeaderText = headerName;
column.Name = "col" + headerName;
dgvMain.Columns.Add(column);
}
用法然后变为
DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
AddColumnHeader(col, "Header name");
Jonathon Reinhart使用扩展方法有一个更清洁的解决方案,我建议一起使用。
答案 1 :(得分:1)
我会在generic上使用Extension Method DataGridView
:
public static class ExtensionMethods {
public static void AddColumn<TCol>(this DataGridView dgv, string headerName)
where TCol : DataGridViewColumn, new()
{
var col = new TCol {
HeaderText = headerName,
Name = "col" + headerName,
};
dgv.Columns.Add(col);
}
}
TCol
上有一个constraint,可确保它是DataGridViewColumn
的子类。
调用扩展方法:
dgvMain.AddColumn<DataGridViewLinkColumn>(headerName);
答案 2 :(得分:0)
假设所有这些类共享一个接口或超类(看起来他们可能会这样做),你可以编写类似的东西:
void AddColumns(params ColumnSuperType[] columns) {
for...
}
其中“ColumnSuperType”是相关父类型或接口的任何内容。
然后你可以做
AddColumns(new DataGridViewTextBoxColumn(), new DataGridViewComboBoxColumn(), etc)
答案 3 :(得分:0)
所有列对象都是从DataGridViewColumn派生的,请尝试以下方法:
private void yourMethode(DataGridViewColumn col)
{
col.HeaderText = headerName;
col.Name = "col" + headerName;
dgvMain.Columns.Add(col);
}