1

我一直在尝试找到一种方法来从选定的ListView行中读取数据,并以他们尊重TextBox的方式显示每个值以便于编辑。

第一种也是最简单的方法是这样的:

ListViewItem item = listView1.SelectedItems[0];

buyCount_txtBox.Text = item.SubItems[1].Text;
buyPrice_txtBox.Text = item.SubItems[2].Text;
sellPrice_txtBox.Text = item.SubItems[3].Text;

该代码没有任何问题,但我有大约 40 个或更多TextBoxes应该显示数据。编码全部 40 个左右会变得非常乏味。

我想出的解决方案是让TextBox我的用户控件中的所有控件如下所示:

    foreach (Control c in this.Controls)
    {
        foreach (Control childc in c.Controls)
        {
            if (childc is TextBox)
            {
            }
        }
    }

然后我需要循环选定的ListView行列标题。如果他们的列标题与 TextBox.Tag 匹配,则在他们尊重的 TextBox 中显示列值。

最终代码如下所示:

    foreach (Control c in this.Controls)
    {
        foreach (Control childc in c.Controls)
        {

          // Needs another loop for the selected ListView Row

            if (childc is TextBox && ColumnHeader == childc.Tag)
            {
               // Display Values
            }
        }
    }

那么我的问题是:如何遍历选定的ListView行和每个列标题。

4

1 回答 1

1

循环遍历你的ColumnHeaders 方法很简单:

foreach(  ColumnHeader  lvch  in listView1.Columns)
{
    if (lvch.Text == textBox.Tag) ; // either check on the header text..
    if (lvch.Name == textBox.Tag) ; // or on its Name..
    if (lvch.Tag  == textBox.Tag) ; // or even on its Tag
}

但是,即使它有效,你循环的方式TextBoxes也不是很好。我建议您将每个参与者添加TextBoxesList<TextBox>. 是的,这意味着添加 40 个项目,但您可以AddRange像这样使用:

要填写 myBoxes 列表:

List<TextBox> myBoxes = new List<TextBox>()

public Form1()
{
    InitializeComponent();
    //..
    myBoxes.AddRange(new[] {textBox1, textBox2, textBox3});
}

或者,如果你真的想避免AddRange并保持动态,你也可以写一个小递归..:

private void CollectTBs(Control ctl, List<TextBox> myBoxes)
{
    if (ctl is TextBox) myBoxes.Add(ctl as TextBox);
    foreach (Control c in ctl.Controls) CollectTBs(c, myBoxes);
}

现在你的最后一个循环又小又快:

foreach(  ColumnHeader  lvch  in listView1.Columns)
{
    foreach (TextBox textBox in myBoxes)
        if (lvch.Tag == textBox.Tag)  // pick you comparison!
            textBox.Text = lvch.Text;
}

更新:由于您实际上想要这些SubItem值,因此解决方案可能如下所示:

ListViewItem lvi = listView1.SelectedItems[0];
foreach (ListViewItem.ListViewSubItem lvsu in  lvi.SubItems)
    foreach (TextBox textBox in myBoxes)
       if (lvsu.Tag == textBox.Tag)  textBox.Text = lvsu.Text;
于 2015-05-16T06:55:06.503 回答