在DataGridView指定行添加ComboBox

来源:互联网 发布:帝国cms 中华养生 编辑:程序博客网 时间:2024/05/16 10:59
表格样式
------------------------------------------
       列1             ||            列2
------------------------------------------
    静态标签      ||         TextBox  
------------------------------------------
    静态标签      ||     ComboBox  
------------------------------------------
    静态标签      ||     ComboBox  
------------------------------------------
代码
       System.Windows.Forms.ComboBox ComboBox1;

        
private void Form1_Load(object sender, EventArgs e)
        
{
            ComboBox1 
= new ComboBox();
            ComboBox1.FormattingEnabled 
= true;
            ComboBox1.Items.AddRange(
new object[] {
            
"1",
            
"2",
            
"3",
            
"4",
            
"5",
            
"6"}
);
            ComboBox1.Name 
= "ComboBox1";
            ComboBox1.TextChanged 
+= new System.EventHandler(this.ComboBox1_TextChanged);
            
this.DataGridView1.Controls.Add(this.ComboBox1);

            
this.DataGridView1.AllowUserToResizeRows = false;
            
this.DataGridView1.AllowUserToResizeColumns = false;
            
this.DataGridView1.Columns.Add("Column1""Column1");
            
this.DataGridView1.Columns.Add("Column2""Column2");
            
for (int i = 1; i <= 3; i++)
            
{
                
this.DataGridView1.Rows.Add("" + i.ToString() + " 列1"""+ i.ToString() + " 列2");
            }

            
this.ComboBox1.Visible = false;
            
        }

        
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        
{
            
if (e.ColumnIndex == 1)
            
{
                
switch (e.RowIndex)
                
{
                    
case 1:
                    
case 2:
                        
this.ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
                        
break;
                    
default:
                        
this.ComboBox1.Visible = false;
                        
return;  
                }

                Point p 
= this.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Location;
                
this.ComboBox1.Location = p;
                
this.ComboBox1.Size = this.DataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Size;
                
this.ComboBox1.Visible = true;
            }

            
else
            
{
                
this.ComboBox1.Visible = false;
            }
 
        }

       
private void ComboBox1_TextChanged(object sender, EventArgs e)
        
{
            
this.DataGridView1.CurrentCell.Value = this.ComboBox1.Text;
        }
原创粉丝点击