2012-07-16 67 views
0

我怎樣才能得到一列可以包含一個文本框或圖像? 我想將任何類型的數據添加到那一列,它是文本或圖像。我將如何在C#中執行此操作?C#中的Datagridview列?

好的,以編程方式,我將有兩個文本框和圖像在同一列...我該怎麼做?

+1

這是問就在幾天前,交替DataGridView的文本和圖像細胞:http://stackoverflow.com/questions/11481142/c-sharp-datagridview-image-and-text-on -th-same-row/11481229#comment15162135_11481229 - 如果你想要文本和圖像結合讓我們知道。 – 2012-07-16 01:44:20

回答

2

下面是一個例子。但是,您將需要處理默認圖像(如果不存在,它將會有交叉標記的圖像)。請參閱本MSDN link

private void Form1_Load(object sender, EventArgs e) 
    { 
     DataTable dataTable = new DataTable(); 
     dataTable.Columns.Add("Name"); 
     dataTable.Columns.Add("Image"); 

     dataTable.Rows.Add("Desert", @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"); 
     dataTable.Rows.Add("Tulips", @"C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg"); 

     dataTable.AcceptChanges(); 

     DataGridViewTextBoxColumn textColumn = new DataGridViewTextBoxColumn(); 
     textColumn.DataPropertyName = "Name"; 
     textColumn.HeaderText = "Name"; 
     textColumn.Width = 100; 
     dataGridView1.Columns.Add(textColumn); 

     DataGridViewImageColumn imageColumn = new DataGridViewImageColumn(); 
     imageColumn.DataPropertyName = "Image"; 
     imageColumn.HeaderText = "Image"; 
     imageColumn.Width = 100;    
     dataGridView1.Columns.Add(imageColumn); 

     dataGridView1.DataSource = dataTable; 
    } 

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     if (this.dataGridView1.Columns[e.ColumnIndex] is DataGridViewImageColumn) 
     { 
      string imagePath = (e.Value ?? "").ToString().Trim(); 
      if(System.IO.File.Exists(imagePath)) 
       e.Value = Image.FromFile(imagePath); 
     } 
    } 
0

要在DataGridView中添加TextBox控件,請單擊智能標記並選擇添加列。選擇DataGridViewTextColumn並單擊添加。如果您選擇圖像,請選擇DataGridViewImageColumn

enter image description here

+0

這並不顯示OP如何同時在同一列中同時顯示文本框和圖像... – 2012-07-16 01:45:15