有时在datagridview中会显示下拉框,方便修改数据,但又不想有下拉框的列在浏览状态全显示有下拉框,如果多列有下拉框会非常难看,
因此就用combox的显示与否来控制,如下图(Factory_ID显示工厂ID号,当此列的单元格获取焦点时,此单元格显示下拉框)
代码如下:
public partial class Form1 : Form { private static string oraclestr = @"(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 10.1.225.255)(PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = testdb) ) )"; static string ConnectStr = string.Format("Data Source={0};User ID={1};Password={2}", oraclestr,"userid","password"); DataTable dt = new DataTable(); DataTable dtlst = new DataTable(); OracleConnection conn = new OracleConnection(ConnectStr); private DataTable GetTable(string sql) { DataTable dt = new DataTable(); try { conn.Open(); OracleCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; OracleDataAdapter oda = new OracleDataAdapter(cmd); oda.Fill(dt); } catch(Exception ex) { throw new Exception(ex.Message); } finally { conn.Close(); } return dt; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = GetTable("select work_order,factory_id from g_wo_base where rownum<=50"); //設置下拉框數據源 comboBox1.DataSource = GetTable("SELECT factory_id,factory_code FROM SYS_FACTORY"); comboBox1.DisplayMember = "factory_code"; comboBox1.ValueMember = "factory_id"; comboBox1.Visible = false; //将下拉框嵌入到表格中 dataGridView1.Controls.Add(comboBox1); } private void SelectIndexChange(object sender,EventArgs e) { //更改dataGridView中的值為下拉框所選的值 ComboBox cmb = (ComboBox)sender; if (cmb == null) return; if (dataGridView1.CurrentCell.Value != cmb.SelectedValue) dataGridView1.CurrentCell.Value = cmb.SelectedValue; } private void dataGridView1_CurrentCellChanged(object sender, EventArgs e) { if (dataGridView1.CurrentCell == null) return; //點擊表頭(header)時,CurrentCell為null int row = dataGridView1.CurrentCell.RowIndex; int col = dataGridView1.CurrentCell.ColumnIndex; if (row != -1 && col ==1) { if (comboBox1.SelectedValue != dataGridView1.CurrentCell.Value) { //在賦值前防止SelectedIndexChanged事件觸發產生錯誤 comboBox1.SelectedIndexChanged -= null; comboBox1.SelectedValue = dataGridView1.CurrentCell.Value; comboBox1.SelectedIndexChanged += SelectIndexChange; } //顯示下拉框 Rectangle rec = dataGridView1.GetCellDisplayRectangle(col, row, true); comboBox1.Location = rec.Location; comboBox1.Size = rec.Size; comboBox1.Visible = true; } else comboBox1.Visible = false; } }