• Курсы Академии Кодебай, стартующие в мае - июне, от команды The Codeby

    1. Цифровая криминалистика и реагирование на инциденты
    2. ОС Linux (DFIR) Старт: 16 мая
    3. Анализ фишинговых атак Старт: 16 мая Устройства для тестирования на проникновение Старт: 16 мая

    Скидки до 10%

    Полный список ближайших курсов ...

Проблема с Listview :)

  • Автор темы ArtUrlWWW
  • Дата начала
Статус
Закрыто для дальнейших ответов.
A

ArtUrlWWW

Здравствуйте.
Столкнулся с таким элементом как listView.
Затея:
1. Поставить на форме listView с 3-мя столбцами - сделал еле как...
Код:
listView1.Columns.Add("id", (int)(listView1.Width / 3));
listView1.Columns.Add("filename", (int)(listView1.Width / 3));
listView1.Columns.Add("filesize", (int)(listView1.Width / 3));
string a = "";
string a1 = "";
string b = "";
for (int x = 0; x < 15; x++)
{
a1 = "ID " + Convert.ToString(x);
a = "Item " + Convert.ToString(x);
b = "SubItem " + Convert.ToString(x);
ListViewItem item = new ListViewItem(a1);
item.SubItems.Add(a);
item.SubItems.Add(b);
this.listView1.Items.Add(item);
}

Так вот. как обратиться к столбцам строки, т.е., примеру:
string a = listView.выделенная_строка.столбец;
или
int a = ConvertToString(listView.выделенная_строка.столбец );
???
Поможите :rolleyes: пожалуйста, кто знает?
 
A

ArtUrlWWW

Сам писал. Вопрос уже решён, спасибо за информацию и за сарказм. До свидания.
 
@

@LE}{@NDER

Раз уж речь пошла о ListView, спрошу и я. Написал программу, которая отображает данные (скажем об автомобилях) в листвью, позволяет, добавлять, удалять и редактировать данные. Редактирование осуществляется созданием в нужной ячейке ТекстБокса или КомбоБокса. Теперь проблема ширина подставляемых элементов расчитывается корректно, до тех пор, пока я не изменяю ширину столбцов. В противоположном случае, корректно вычисляется ширина подставляемых элементов только первого столбца, все остальные подставляемые элементы смещены. Как решить эту проблему?

Функционал ListView а также подставляемых элементов зашит в классе EditListView унаследованном от ListView

[codebox]using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;

namespace CarReferenceBook
{
class EditListView : ListView
{
private ListViewItem li;
private int X=0;
private int Y=0;
private string subItemText;
private int subItemSelected = 0;
private System.Windows.Forms.TextBox editBox = new System.Windows.Forms.TextBox();
private System.Windows.Forms.ComboBox cmbBox = new System.Windows.Forms.ComboBox();

public EditListView()
{
cmbBox.Items.Add("Внедорожник");
cmbBox.Items.Add("Кабриолет");
cmbBox.Items.Add("Купе");
cmbBox.Items.Add("Лифтбек");
cmbBox.Items.Add("Минивен");
cmbBox.Items.Add("Пикап");
cmbBox.Items.Add("Седан");
cmbBox.Items.Add("Универсал");
cmbBox.Items.Add("Фургон");
cmbBox.Items.Add("Хэтчбэк");

cmbBox.Size = new System.Drawing.Size(0,0);
cmbBox.Location = new System.Drawing.Point(0,0);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.cmbBox});
cmbBox.SelectedIndexChanged += new System.EventHandler(this.CmbSelected);
cmbBox.LostFocus += new System.EventHandler(this.CmbFocusOver);
cmbBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.CmbKeyPress);
cmbBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
cmbBox.BackColor = Color.SkyBlue;
cmbBox.DropDownStyle = ComboBoxStyle.DropDownList;
cmbBox.Hide();


this.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.FullRowSelect = true;
this.Size = new System.Drawing.Size(619, 380);

this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.SMKMouseDown);
this.DoubleClick += new System.EventHandler(this.SMKDoubleClick);
this.GridLines = true;
System.Windows.Forms.ColumnHeader columnMark = new System.Windows.Forms.ColumnHeader();
System.Windows.Forms.ColumnHeader columnModel = new System.Windows.Forms.ColumnHeader();
System.Windows.Forms.ColumnHeader columnCarBody = new System.Windows.Forms.ColumnHeader();
System.Windows.Forms.ColumnHeader columnEngine = new System.Windows.Forms.ColumnHeader();
System.Windows.Forms.ColumnHeader columnProductionYear = new System.Windows.Forms.ColumnHeader();
System.Windows.Forms.ColumnHeader columnWeight = new System.Windows.Forms.ColumnHeader();

this.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
columnMark,
columnModel,
columnCarBody,
columnEngine,
columnProductionYear,
columnWeight});
this.FullRowSelect = true;
this.GridLines = true;
this.Location = new System.Drawing.Point(12, 12);
this.Name = "listView1";
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
//this.Size = new System.Drawing.Size(542, 337);
this.TabIndex = 1;
this.UseCompatibleStateImageBehavior = false;
this.View = System.Windows.Forms.View.Details;
//
// columnMark
//
columnMark.Text = "Марка";
//
// columnModel
//
columnModel.Text = "Модель";
//
// columnCarBody
//
columnCarBody.Text = "Тип кузова";
//
// columnEngine
//
columnEngine.Text = "Объём двигателя, L";
//
// columnProductionYear
//
columnProductionYear.Text = "Год выпуска";
//
// columnWeight
//
columnWeight.Text = "Масса, кг";

for (int i=0; i<Columns.Count; i++)
{
Columns.Width=this.Width/Columns.Count;
}
editBox.Size = new System.Drawing.Size(0,0);
editBox.Location = new System.Drawing.Point(0,0);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.editBox});
editBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.EditOver);
editBox.LostFocus += new System.EventHandler(this.FocusOver);
editBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
editBox.BackColor = Color.LightYellow;
editBox.BorderStyle = BorderStyle.Fixed3D;
editBox.Hide();
editBox.Text = "";

}

private void CmbKeyPress(object sender , System.Windows.Forms.KeyPressEventArgs e)
{
if ( e.KeyChar == 13 || e.KeyChar == 27 )
{
cmbBox.Hide();
}
}

private void CmbSelected(object sender , System.EventArgs e)
{
int sel = cmbBox.SelectedIndex;
if ( sel >= 0 )
{
string itemSel = cmbBox.Items[sel].ToString();
li.SubItems[subItemSelected].Text = itemSel;
}
}

private void CmbFocusOver(object sender , System.EventArgs e)
{
cmbBox.Hide();
}
private void EditOver(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ( e.KeyChar == 13 )
{
li.SubItems[subItemSelected].Text = editBox.Text;
editBox.Hide();
}

if ( e.KeyChar == 27 )
editBox.Hide();
}

private void FocusOver(object sender, System.EventArgs e)
{
li.SubItems[subItemSelected].Text = editBox.Text;
editBox.Hide();
}

public void SMKDoubleClick(object sender, System.EventArgs e)
{
// Check the subitem clicked .
int nStart = X;
int spos = 0;
int epos = this.Columns[0].Width;
for ( int i=0; i < this.Columns.Count; i++)
{
if ( nStart > spos && nStart < epos )
{
subItemSelected = i;
break;
}

spos = epos;
epos += this.Columns.Width;
}

Console.WriteLine("SUB ITEM SELECTED = " + li.SubItems[subItemSelected].Text);
subItemText = li.SubItems[subItemSelected].Text;

string colName = this.Columns[subItemSelected].Text;
if ( colName == "Тип кузова" )
{
Rectangle r = new Rectangle(spos , li.Bounds.Y , epos , li.Bounds.Bottom);
cmbBox.Size = new System.Drawing.Size(epos - spos , li.Bounds.Bottom-li.Bounds.Top);
cmbBox.Location = new System.Drawing.Point(spos , li.Bounds.Y);
cmbBox.Show();
cmbBox.Text = subItemText;
cmbBox.SelectAll();
cmbBox.Focus();
}
else
{
Rectangle r = new Rectangle(spos , li.Bounds.Y , epos , li.Bounds.Bottom);
editBox.Size = new System.Drawing.Size(epos - spos, li.Bounds.Bottom-li.Bounds.Top);
editBox.Location = new System.Drawing.Point(spos, li.Bounds.Y);
editBox.Show();
editBox.Text = subItemText;
editBox.SelectAll();
editBox.Focus();
}
}

public void SMKMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
li = this.GetItemAt(e.X , e.Y);
X = e.X;
Y = e.Y;
}
}
}[/codebox]

ЗЫ: Попрошу сильно не придираться к коду, я на .Net только 2 месяца пишу, раньше писал на С++
 
Статус
Закрыто для дальнейших ответов.
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!