【发布时间】:2019-01-30 03:33:11
【问题描述】:
我有一个带有搜索按钮和进度条的表单,用于在网络目录中查找照片。 它返回一个错误:
System.Reflection.TargetInvocationException
HResult=0x80131604
Message=O destino de uma invocação accionou uma excepção.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at _myprogram.Program.Main() in C:\Users\folder\Desktop\folder\folder\V10\folder\Program.cs:line 19
Inner Exception 1:
ArgumentOutOfRangeException: O índice estava fora do intervalo. Tem de ser não negativo e inferior ao tamanho da colecção.
Nome do parâmetro: índex
代码如下:
public partial class FormProcuraFotos : Form
{
public FormProcuraFotos()
{
InitializeComponent();
}
// We create the DataTable here so we can create the new inside the Worker_DoWork and use it also on the Worker_RunWorkerCompleted
DataTable tableWithPhotos;
private void button1_Click(object sender, EventArgs e)
{
// Make the progressBar1 to look like its allways loading something
progressBar1.Style = ProgressBarStyle.Marquee;
// Make it here visible
progressBar1.Visible = true;
var worker = new BackgroundWorker();
// Event that runs on background
worker.DoWork += this.Worker_DoWork;
// Event that will run after the background event as finnished
worker.RunWorkerCompleted += this.Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
// The reason for having this here was to work with the progress bar and to search for the photos and it will not block the UI Thread
// My advice is to have them here and pass them to the next form with a constructor
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// We must create a list for all the files that the search it will find
List<string> filesList = new List<string>();
// Create the new DataTable to be used
tableWithPhotos = new DataTable();
tableWithPhotos.Columns.Add("Nome e formato do ficheiro (duplo clique para visualizar a imagem)");
tableWithPhotos.Columns.Add("Caminho ( pode ser copiado Ctrl+C )");
// What folders that we want to search for the files
var diretorios = new List<string>() { @"C:\Users\folder\Pictures" };
// What extensions that we want to search
var extensoes = new List<string>() { ".jpg", ".bmp", ".png", ".tiff", ".gif" };
// This 2 foreach are to search for the files with the extension that is on the extensoes and on all directories that are on diretorios
// In for foreach we go through all the extensions that we want to search
foreach (string entryExtensions in extensoes)
{
// Now we must go through all the directories to search for the extension that is on the entryExtensions
foreach (string entryDirectory in diretorios)
{
// SearchOption.AllDirectories search the directory and sub directorys if necessary
// SearchOption.TopDirectoryOnly search only the directory
filesList.AddRange(Directory.GetFiles(entryDirectory, entryExtensions, SearchOption.AllDirectories));
}
}
// And now here we will add all the files that it has found into the DataTable
foreach (string entryFiles in filesList)
{
DataRow row = tableWithPhotos.NewRow();
row[0] = Path.GetFileName(entryFiles);
row[1] = entryFiles;
tableWithPhotos.Rows.Add(row);
}
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// With the new constructor on the FormResultadosFotos, we pass the table like this so the form can receive it
progressBar1.Visible = false;
var NovoForm = new FormResultadosFotos(tableWithPhotos);
NovoForm.Show();
}
}
} 我有另一个表单可以在 datagridview 上显示这些结果(这个 datagridview 有一个图片框,如果用户双击则显示照片) 代码如下:
public partial class FormResultadosFotos : Form
{
// This is the constructor that we have added to the FormResultadosFotos so it can receive the DataTable that was created on the previous form
public FormResultadosFotos(DataTable table)
{
InitializeComponent();
dataGridView1.DataSource = table;
dataGridView1.Columns[1].Visible = true;
// What can be done here to not block the UI thread if is being blocked while populating the dataGridView1, is to create another BackgroundWorker here and populate the dataGridView1 there
}
}
}
是否可以帮助我并说明问题所在?谢谢。
【问题讨论】:
-
你没有描述问题是什么,你只是给了我们两个(大)代码块并说“出了什么问题?”请更新您的问题,说明问题是什么以及您预计会发生什么。
-
请不要包含任何与问题没有直接关系的代码。空方法就是其中之一。他们所做的只是占用空间。
-
这来自他提出的另一个问题,stackoverflow.com/questions/51984123/…