Простой вопрос о WinForms и ListView - PullRequest
1 голос
/ 14 июня 2010

У меня есть ListView в моем приложении WinForms.ListWiew имеет 4 столбца.Поэтому я хочу написать строку в четвертом столбце на каждом LisViewItem.Когда я пытаюсь это сделать.

foreach (ListViewItem item in lvData.Items)
                {
                    item.SubItems[3].Text ="something";
                }

я получаю исключение

InvalidArgument=Value of '4' is not valid for 'index'.
Parameter name: index

Что не так?

Стек вызовов:

Подсказчик.exe! Suggester.MainForm.btnSend_Click (отправитель объекта = {Text = "Отправить"}, System.EventArgs e = {X = 45 Y = 15 Button = Left}) Строка 316 C # System.Windows.Forms.dll! System.Windows.Forms.Control.OnClick (System.EventArgs e) + 0x70 байт
System.Windows.Forms.dll! System.Windows.Forms.Button.OnClick (System.EventArgs e) + 0x4a байт
System.Windows.Forms.dll! System.Windows.Forms.Button.OnMouseUp (System.Windows.Forms.MouseEventArgs mevent = {X = 45 Y = 15 Button = Left}) + 0xac байтов System.Windows.Forms.dll! System.Windows.Forms.Control.WmMouseUp (ref System.Windows.Forms.Message m, кнопка System.Windows.Forms.MouseButtons, щелчки int) + 0x28f байт System.Windows.Forms.dll! System.Windows.Forms.Control.WndProc (ref System.Windows.Forms.Message m) + 0x885 байт System.Windows.Forms.dll! System.Windows.Forms.ButtonBase.WndProc (ref System.Windows.Forms.Message m) + 0x127 байт
System.Windows.Forms.dll! System.Windows.Forms.Button.WndProc (ref System.Windows.Forms.Message m) + 0x20 байт
System.Windows.Forms.dll! System.Windows.Forms.Control.ControlNativeWindow.OnMessage (ref System.Windows.Forms.Message m) + 0x10 байт
System.Windows.Forms.dll! System.Windows.Forms.Control.ControlNativeWindow.WndProc (ref System.Windows.Forms.Message m) + 0x31 байт
System.Windows.Forms.dll! System.Windows.Forms.NativeWindow.DebuggableCallback (System.IntPtr hWnd, int msg = 514, System.IntPtrwparam, System.IntPtr lparam) + 0x57 байт
[Собственный для управляемого перехода]
[Управляемый для собственного перехода]
System.Windows.Forms.dll! System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop (int dwComponentID, int reason = -1, int pvLoopData = 0) + 0x24e байтовint reason = -1, System.Windows.Forms.ApplicationContext context = {System.Windows.Forms.ApplicationContext}) + 0x177 байт System.Windows.Forms.dll! System.Windows.Forms.Application.ThreadContext.RunMessageLoop (int reason, Контекст System.Windows.Forms.ApplicationContext) + 0x61 байт
System.Windows.Forms.dll! System.Windows.Forms.Application.Run (System.Windows.Forms.Form mainForm) + 0x31 байт
советчик.exe! Suggester.Program.Main () Строка 17 + 0x1d байт C # [Собственный для управляемого перехода]
[Управляемый для собственного перехода]
mscorlib.dll! System.AppDomain.ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence AssemblySecurity, string [] args) + 0x3a байт
Microsoft.VisualStudio.HostingProcess.Utilities.dll! Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly () + 0x2b байт
mscorlib.dll!Threading.ThreadHelper.ThreadStart_Context (состояние объекта) + 0x66 байт
mscorlib.dll! System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executeContext, обратный вызов System.Threading.ContextCallback, состояние объекта) + 0x6f байт
mscorlib.dll! System.Threading.ThreadHelper.ThreadStart () + 0x44 байт

Ответы [ 2 ]

0 голосов
/ 14 июня 2010

Есть ли у каждого элемента в вашем списке три подпункта?Вы не можете просто установить количество столбцов, вам нужно добавить необходимые подпункты для каждого добавленного элемента.Даже если они пусты, вам все равно нужно добавить их для доступа к ним.

foreach (ListViewItem item in lvData.Items) 
            { 
                while(item.SubItems.Count() < 3)
                {
                     item.SubItems.Add("");
                }
                item.SubItems[3].Text ="something"; 
            } 
0 голосов
/ 14 июня 2010

Причина, по которой вы получаете эту ошибку, заключается в том, что в столбце 4 отсутствует элемент. Это как если бы вы пытались вызвать объект, который не был создан.

Предположим, вы добавили данные в первые 3 столбца, как это .....

 ListViewItem item1 = new ListViewItem("Col 1", 0);
 item1.SubItems.Add("Col 2");
 item1.SubItems.Add("Col 3");

и после определенного события, например, нажатия кнопки, вы хотите добавить что-то в столбец 4 всех элементов, затем вы можете использовать следующий код.

foreach (ListViewItem l in listView1.Items)
{
  l.SubItems.Add("Col 4");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...