I've been trying to find out a way to read data from the selected ListView
row and display each value in their respected TextBox
for easy editing.
The first and easiest way would be something like this:
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;
There is nothing wrong with that code but I have around 40 or more TextBoxes
that should display data. Coding all 40 or so would become very tedious.
The solution I've come up with, is to get all TextBox
Controls in my User Control like so:
foreach (Control c in this.Controls)
{
foreach (Control childc in c.Controls)
{
if (childc is TextBox)
{
}
}
}
Then I need to loop the selected ListView
row column headers. If their column header matches TextBox.Tag then display the column value in their respected TextBox.
The final code would look something like this:
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
}
}
}
So then my question would be: How can I loop through the selected ListView
Row and each column header.
Looping over your
ColumnHeaders
is simply done like this:However the way you loop over your
TextBoxes
is not exactly nice even if it works. I suggest that you add each of the participatingTextBoxes
into aList<TextBox>
. Yes, that means to add 40 items, but you can useAddRange
maybe like this:To fill a list myBoxes:
Or, if you really want to avoid the
AddRange
and also stay dynamic, you can also write a tiny recursion..:Now your final loop is slim and fast:
Update: since you actually want the
SubItem
values the solution could look like this: