1.效果:
2.点击‘配置’按钮;
private void btn_configure_Click(object sender, EventArgs e)
{
string sum = string.Empty;
string id = string.Empty;
//将显示在界面上的dgv字段列串联起来,作为字符串传到另外一个‘配置’界面
DataTable dt = (DataTable)Dgv.DataSource;
for (int i = ; i < Dgv.ColumnCount; i++)
{
string s = Dgv.Columns[i].HeaderText;
sum += s + ",";
if (Dgv.Columns[i].Visible == true)
{
id += i + ",";
}
}
Frm配置 frm = new Frm配置();
frm.data = sum;
frm.id = id;
frm.TransfEvent += frm_TransfEvent;
frm.ShowDialog();
BindDGVColumns(); }
3.在‘配置界面’循环出dgv的字段列名并绑定在‘配置界面’的dgv上,并对字段列判断是否需要checked;
public partial class Frm配置 : Form
{
public delegate void TransfDelegate(String value);
public event TransfDelegate TransfEvent;
public Frm配置()
{
InitializeComponent();
}
public string data { get; set; }
public string id { get; set; }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string sum = string.Empty;
for (int i = ; i < dgv.Rows.Count; i++) {
if ((bool)dgv.Rows[i].Cells[].EditedFormattedValue == true) {
string s =Convert.ToString(dgv.Rows[i].Cells[].Value);
sum += s + ",";
}
}
TransfEvent(sum);
} private void Frm配置_Load(object sender, EventArgs e)
{
string[] s = data.Split(',');
26 for (int j = 0; j < s.Length; j++)
{
string name = s[j].ToString();
if (name != "") {
// 首先 声明一个 DataGridViewRow 对象 (即要添加的行)
DataGridViewRow dr = new DataGridViewRow();
//设置要添加行的列
DataGridViewCheckBoxCell check = new DataGridViewCheckBoxCell();
DataGridViewTextBoxCell text = new DataGridViewTextBoxCell();
dr.Cells.Add(check);
dr.Cells.Add(text);
//设置列的值 //将声明的行添加到dataGridView1 中
dgv.Rows.Add(dr);
dgv.Rows[j].Cells[].Value = false;
dgv.Rows[j].Cells[].Value = name;
}
}
string[] idsum = id.Split(',');
for (int i = ; i < idsum.Length; i++)
{
string ids = idsum[i].ToString();
if (ids != "") {
int id = Convert.ToInt32(ids);
dgv.Rows[id].Cells[].Value = true;
}
}
}
}
4.根据‘配置界面’穿过来的字符串,循环显示字段列在dgv上面
public int id;
public static string name;
private void BindDGVColumns()
{
for (int j = ; j < Dgv.ColumnCount; j++)
{
Dgv.Columns[j].Visible = false;
}
string[] s = name.Split(',');
for (int i = ; i <s.Length; i++)
{
bool falg = false;
string name = s[i].ToString();
if (name != "")
{
for (int j = ; j < Dgv.ColumnCount; j++)
{
id = j;
string dgvcname = Dgv.Columns[j].HeaderText;
if (name == dgvcname)
{
falg = true;
break;
}
}
if (falg == true)
{
Dgv.Columns[id].Visible = true;
} }
}
}