简体   繁体   中英

Datagridview column in C#?

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?

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);
        }
    }

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.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM