0

我怎样才能让一列能够包含文本框或图像?我正在尝试向该列添加任何类型的数据,无论是文本还是图像。我将如何在 C# 中执行此操作?

好的,以编程方式,我将在同一列中同时拥有文本框和图像......我该怎么做?

4

2 回答 2

2

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);
        }
    }
于 2012-07-16T01:47:21.913 回答
0

要在 中添加TextBox控件DataGridView,请单击智能标记并选择添加列。选择DataGridViewTextColumn并单击添加。选择DataGridViewImageColumn是否选择图像。

在此处输入图像描述

于 2012-07-16T01:28:19.140 回答