如图片所示,dataGridView添加了如下的列,默认第三列开始后面的4列SHORT-NAME,CATEGORY,ARRAY-SIZE,ARRAY-SIZE-SEMANTICS的不可见,即Visible属性为false;已经设置好。
现在需求如下,当第二列的值,选中ARRAY之后,
从第三列开始后面的4列SHORT-NAME,CATEGORY,ARRAY-SIZE,ARRAY-SIZE-SEMANTICS的Visible属性变为true
如图片所示,dataGridView添加了如下的列,默认第三列开始后面的4列SHORT-NAME,CATEGORY,ARRAY-SIZE,ARRAY-SIZE-SEMANTICS的不可见,即Visible属性为false;已经设置好。
现在需求如下,当第二列的值,选中ARRAY之后,
从第三列开始后面的4列SHORT-NAME,CATEGORY,ARRAY-SIZE,ARRAY-SIZE-SEMANTICS的Visible属性变为true
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Q691015
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add(new DataGridViewComboBoxColumn() { Name = "col1", HeaderText = "category", ValueType = typeof(string) });
dataGridView1.Columns.Add("col2", "short name");
dataGridView1.Columns[1].Visible = false;
dataGridView1.CellEnter += new DataGridViewCellEventHandler(dataGridView1_CellEnter);
dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
//防止用户切换到另外一行,并且这一列选择的不是array
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != null && e.ColumnIndex != 0)
{
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() != "array")
{
e.Cancel = true;
}
}
}
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox)
{
var cbo = e.Control as ComboBox;
cbo.TextChanged += new EventHandler(cbo_TextChanged);
}
}
//设置是否可见
void cbo_TextChanged(object sender, EventArgs e)
{
if ((sender as ComboBox).Text == "array")
dataGridView1.Columns[1].Visible = true;
else
dataGridView1.Columns[1].Visible = false;
}
void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
cell.Items.Clear();
cell.Items.Add("none");
cell.Items.Add("array");
}
}
}
}