You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#开发:如何从DataGridView选中项显示文件夹/嵌入资源图片到PictureBox并实现图片替换

嘿,我来帮你搞定这两个问题,咱们一步步拆解:

问题1:根据DataGridView选中行显示本地文件夹的图片

首先你需要给dataGridView1绑定SelectionChanged事件,这样用户选中不同行时,就能自动触发图片加载逻辑。

步骤1:绑定事件

你可以在窗体构造函数里手动绑定,或者在设计器里双击dataGridView1的SelectionChanged事件生成方法:

public YourFormName()
{
    InitializeComponent();
    // 绑定选中变更事件
    dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}

步骤2:实现图片加载逻辑

在事件处理方法里,获取选中行的文件名,拼接完整路径后加载到PictureBox:

private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    // 确保有选中的行
    if (dataGridView1.SelectedRows.Count <= 0) return;

    // 获取选中行的文件名
    string fileName = dataGridView1.SelectedRows[0].Cells["File Name"].Value.ToString();
    // 用Path.Combine拼接路径,比直接字符串拼接更安全
    string fullImagePath = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
        "Black Desert",
        "FaceTexture",
        fileName
    );

    try
    {
        // 加载图片到PictureBox
        pictureBox1.Image = Image.FromFile(fullImagePath);
        // 设置显示模式优化视觉效果,比如Zoom(保持比例缩放)
        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
    }
    catch (Exception ex)
    {
        // 处理加载失败的情况,比如文件损坏、路径错误
        MessageBox.Show($"加载图片出错:{ex.Message}");
        pictureBox1.Image = null;
    }
}

问题2:读取嵌入资源的文件名并显示图片

你现在的代码获取的资源名称是包含完整命名空间的路径(比如YourProjectName.Resources.MyFace.png),直接用FileInfo.Name提取文件名会出问题,而且加载资源图片需要用资源流来读取,咱们一步步修正:

步骤1:修正资源文件名的读取

先过滤掉非图片资源,再提取真实的文件名:

Assembly currentAssembly = Assembly.GetExecutingAssembly();
string[] allResourceNames = currentAssembly.GetManifestResourceNames();
DataTable table2 = new DataTable();
table2.Columns.Add("File Name");

foreach (string resourceName in allResourceNames)
{
    // 只保留图片格式的资源(可根据你的需求调整扩展名)
    string[] validExtensions = { ".png", ".jpg", ".jpeg", ".bmp" };
    if (validExtensions.Any(ext => resourceName.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
    {
        // 从完整资源名中提取真实文件名:拆分后取最后两部分拼接(比如"Resources.MyFace.png" → "MyFace.png")
        string[] nameParts = resourceName.Split('.');
        string fileName = $"{nameParts[nameParts.Length - 2]}.{nameParts[nameParts.Length - 1]}";
        table2.Rows.Add(fileName);
    }
}
dataGridView2.DataSource = table2;

步骤2:绑定选中事件显示资源图片

同样给dataGridView2绑定SelectionChanged事件,然后通过资源流加载图片:

// 先在构造函数里绑定事件
dataGridView2.SelectionChanged += DataGridView2_SelectionChanged;

// 事件处理方法
private void DataGridView2_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridView2.SelectedRows.Count <= 0) return;

    string targetFileName = dataGridView2.SelectedRows[0].Cells["File Name"].Value.ToString();
    Assembly currentAssembly = Assembly.GetExecutingAssembly();

    // 找到对应的完整资源名(通过文件名后缀匹配)
    string fullResourceName = currentAssembly.GetManifestResourceNames()
        .FirstOrDefault(name => name.EndsWith(targetFileName, StringComparison.OrdinalIgnoreCase));

    if (string.IsNullOrEmpty(fullResourceName))
    {
        MessageBox.Show("未找到对应的嵌入资源");
        pictureBox2.Image = null;
        return;
    }

    try
    {
        // 从资源流加载图片,注意要用using释放流资源
        using (Stream resourceStream = currentAssembly.GetManifestResourceStream(fullResourceName))
        {
            if (resourceStream != null)
            {
                pictureBox2.Image = Image.FromStream(resourceStream);
                pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
            }
            else
            {
                MessageBox.Show("无法打开资源流");
                pictureBox2.Image = null;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"加载资源图片出错:{ex.Message}");
        pictureBox2.Image = null;
    }
}

重要提示

别忘了在解决方案资源管理器里,把嵌入的图片文件的生成操作设置为嵌入的资源(右键图片 → 属性 → 生成操作),否则无法通过GetManifestResourceNames获取到资源。


内容的提问来源于stack exchange,提问作者LearningHow2Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:52:37