开发者

C# datagrid index was out of range

开发者 https://www.devze.com 2023-01-28 04:11 出处:网络
keep getting the error for this line: var imagePath = dataGrid1.SelectedItems[5].ToString(); Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: i

keep getting the error for this line:

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

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Trying to store a cell from my datagrid in a var/string (it holds a path+filename) so I can delete it via ftp.

        private void button2_Click(object sender, RoutedEventArgs e)
    {
        var imagePath = dataGrid1.SelectedItems[5].ToString();
        Student selected = dataGrid1.SelectedItem as Student;
        if (selected == null)
     开发者_Go百科       MessageBox.Show("You must select a student");
        else
        {
            if (MessageBoxResult.Yes == MessageBox.Show("Are you sure", "delete student",
                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();
    }

}

}


I think you've got it mixed up between SelectedItems and SelectedItem - SelectedItems should return a IEnumerable of the selected items - it looks like you're trying to access a column of the SelectedItem.

If Student has an ImagePath, you could re-order a little and just have:

Student selected = dataGrid1.SelectedItem as Student;
var imagePath = selected.ImagePath;
0

精彩评论

暂无评论...
验证码 换一张
取 消