Reputation: 7293
how can i get a column to be able to contain a textbox or an image? I am trying to add any type of data to that one column, wether it be text or an image. How would i do this in C#?
ok, programmatically, i am going to have both textboxes and images in the same column...how do i do it?
Upvotes: 0
Views: 1643
Reputation: 4361
Here is an example. However you will need to handle the default image (in absence it is going to have a cross marked image). Refer to this 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);
}
}
Upvotes: 2
Reputation: 5077
To add a TextBox
control inside the DataGridView
, click the smart tag and select Add Column. Select DataGridViewTextColumn
and click Add. Select DataGridViewImageColumn
if you choose image.
Upvotes: 0