1.效果:
2.点击‘配置’按钮;
1 private void btn_configure_Click(object sender, EventArgs e) 2 { 3 string sum = string.Empty; 4 string id = string.Empty;
//将显示在界面上的dgv字段列串联起来,作为字符串传到另外一个‘配置’界面 5 DataTable dt = (DataTable)Dgv.DataSource; 6 for (int i = 0; i < Dgv.ColumnCount; i++) 7 { 8 string s = Dgv.Columns[i].HeaderText; 9 sum += s + ","; 10 if (Dgv.Columns[i].Visible == true) 11 { 12 id += i + ","; 13 } 14 } 15 Frm配置 frm = new Frm配置(); 16 frm.data = sum; 17 frm.id = id; 18 frm.TransfEvent += frm_TransfEvent; 19 frm.ShowDialog(); 20 BindDGVColumns();22 }
3.在‘配置界面’循环出dgv的字段列名并绑定在‘配置界面’的dgv上,并对字段列判断是否需要checked;
1 public partial class Frm配置 : Form 2 { 3 public delegate void TransfDelegate(String value); 4 public event TransfDelegate TransfEvent; 5 public Frm配置() 6 { 7 InitializeComponent(); 8 } 9 public string data { get; set; } 10 public string id { get; set; } 11 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 12 { 13 string sum = string.Empty; 14 for (int i = 0; i < dgv.Rows.Count; i++) { 15 if ((bool)dgv.Rows[i].Cells[0].EditedFormattedValue == true) { 16 string s =Convert.ToString(dgv.Rows[i].Cells[1].Value); 17 sum += s + ","; 18 } 19 } 20 TransfEvent(sum); 21 } 22 23 private void Frm配置_Load(object sender, EventArgs e) 24 { 25 string[] s = data.Split(','); 26 for (int j = 0; j < s.Length; j++) 27 { 28 string name = s[j].ToString(); 29 if (name != "") { 30 // 首先 声明一个 DataGridViewRow 对象 (即要添加的行) 31 DataGridViewRow dr = new DataGridViewRow(); 32 //设置要添加行的列 33 DataGridViewCheckBoxCell check = new DataGridViewCheckBoxCell(); 34 DataGridViewTextBoxCell text = new DataGridViewTextBoxCell(); 35 dr.Cells.Add(check); 36 dr.Cells.Add(text); 37 //设置列的值 38 39 //将声明的行添加到dataGridView1 中 40 dgv.Rows.Add(dr); 41 dgv.Rows[j].Cells[0].Value = false; 42 dgv.Rows[j].Cells[1].Value = name; 43 } 44 } 45 string[] idsum = id.Split(','); 46 for (int i = 0; i < idsum.Length; i++) 47 { 48 string ids = idsum[i].ToString(); 49 if (ids != "") { 50 int id = Convert.ToInt32(ids); 51 dgv.Rows[id].Cells[0].Value = true; 52 } 53 } 54 } 55 }
4.根据‘配置界面’穿过来的字符串,循环显示字段列在dgv上面
1 public int id; 2 public static string name; 3 private void BindDGVColumns() 4 { 5 for (int j = 0; j < Dgv.ColumnCount; j++) 6 { 7 Dgv.Columns[j].Visible = false; 8 } 9 string[] s = name.Split(','); 10 for (int i = 0; i <s.Length; i++) 11 { 12 bool falg = false; 13 string name = s[i].ToString(); 14 if (name != "") 15 { 16 for (int j = 0; j < Dgv.ColumnCount; j++) 17 { 18 id = j; 19 string dgvcname = Dgv.Columns[j].HeaderText; 20 if (name == dgvcname) 21 { 22 falg = true; 23 break; 24 } 25 } 26 if (falg == true) 27 { 28 Dgv.Columns[id].Visible = true; 29 } 30 31 } 32 } 33 } 34