【问题标题】:c# datagrid cell extractionc# datagrid单元格提取
【发布时间】:2025-11-30 18:35:01
【问题描述】:

嘿,我正在尝试将来自选定项目的字符串存储在数据网格中,因为它具有用于删除的文件路径 ID。

我不确定我的做法是否正确。

我的列看起来像这样

|身份证 |用户号 |名字 |姓氏 |当前 |图像路径 |

..01...454656…………哈利…………波特…………巫师……ftp://192.168 .1.8/Jellyfish.jpg

当我删除时,我试图在我的数据网格中“选择”,我也从我的 ftp 服务器中删除。我需要存储在 imagePath coloum 下的信息,这样我就可以进行 ftp 删除。

    private void button2_Click(object sender, RoutedEventArgs e)
{
    string imagePath = dataGrid1.SelectedItems.ToString();
    Student selected = dataGrid1.SelectedItem as Stu;
    if (selected == null)
        MessageBox.Show("You must select a user");
    else
    {
        if (MessageBoxResult.Yes == MessageBox.Show("Are you sure", "delete user",
            MessageBoxButton.YesNo, MessageBoxImage.Warning))
        {
            FTPdelete(imagePath, "Administrator", "commando");
            Class1.DeleteStudent(selected);
            Window_Loaded(null, null);
        }
    }
}
private void FTPdelete(String imagePath, String inUsername, String inPassword)
{
    var req = (FtpWebRequest)WebRequest.Create(imagePath);
    req.Proxy = null;
    req.Credentials = new NetworkCredential(inUsername, inPassword);

    req.Method = WebRequestMethods.Ftp.DeleteFile;

    req.GetResponse().Close();
}

}

}

我得到的错误:

索引超出范围。必须是非负数且小于集合的大小。参数名称:索引

在这一行:

string imagePath = dataGrid1.SelectedItems[6].ToString();

我也试过

var imagePath = dataGrid1.SelectedItems[6].ToString();

不走运:(以为我差点就成功了!!

【问题讨论】:

    标签: c# .net wpf c#-4.0 wpfdatagrid


    【解决方案1】:

    已编辑答案

    很抱歉告诉你我没有玩过 WPF,所以为了你的问题,我不得不稍微玩一下 :) 我回答了你的问题,假设 WPF 与 WinForms 几乎相似。

    这就是答案:)

    DataRowView dr = (DataRowView)(dataGrid1.SelectedItems[0]);
    MessageBox.Show(dr.Row.ItemArray[5].ToString());
    

    dataGrid1.SelectedItems 是一个包含所有选定行的数组。所以你想要第一个。如果您不希望用户选择多于一行,请将SelectionMode 设置为Single

    您首先将 SelectedItem 转换为 DataRowView 类型,然后您可以使用它来访问该特定行的列。

    抱歉迟到了,希望对你有帮助:)

    【讨论】:

    • 没有仍然得到错误:索引超出范围。必须是非负数且小于集合的大小。参数名称:索引
    【解决方案2】:

    您的“SelectedItems[6]”超出范围。请记住,您在数组中以“0”而不是“1”开头。

    string imagePath = dataGrid1.SelectedItems[5].ToString();

    应该可以。

    【讨论】: