kumbhani bhavesh
kumbhani bhavesh

Reputation: 2257

Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.DriveInfo'

 foreach(DriveInfo di in DriveInfo.GetDrives())
        {
            lstdrive.Items.Add(di.ToString());

        }

     lstfolder.Items.Clear();
        try
        {
            DriveInfo drive =(DriveInfo)lstdrive.SelectedItem;
            foreach (DriveInfo diInfo in drive.RootDirectory.GetDirectories())
            {
                lstfolder.Items.Add(diInfo.ToString());
            }
        }
        catch (Exception ex)
        {

            throw ex;
        }

error Error 3 Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.DriveInfo'

Upvotes: 0

Views: 1340

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73751

You can add the DriveInfo items to the list this way:

foreach (DriveInfo di in DriveInfo.GetDrives())
{
    lstdrive.Items.Add(new ListItem(di.ToString(), di.Name));
}

and retrieve the selected drive this way:

DriveInfo drive = new DriveInfo(lstdrive.SelectedValue);

foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
{
    lstfolder.Items.Add(dirInfo.ToString());
}

Upvotes: 1

mohsen
mohsen

Reputation: 1806

You got this error at

 DriveInfo drive =(DriveInfo)lstdrive.SelectedItem;

You can avoid this error by creating a class like

public class MyLi: ListItem
{
    public DriveInfo DI { get; set;}
    public override string ToString()
    {
        return DI.ToString();
    }
}

Use this class

foreach(DriveInfo di in DriveInfo.GetDrives())
{
    MyLi li= new MyLi();
    li.DI= di;
    lstdrive.Items.Add(li);
}

And get your DriveInfo like this

    DriveInfo drive = (lstdrive.SelectedItem as MyLi).DI;

Upvotes: 1

Related Questions