HackTweaks
HackTweaks

Reputation: 73

How to replace value of column in a row in ListView using C#.net?

ID      Item          Code
1       Item a        1565
2       Item x        **2565**
3       Item w        1245
4       Item f        1345

I have a ListView Details format like above and I want to change the value of a cell content which is in between ** mark. How can I change it such a way that it will appear in same row and without need of updating other values in a row or a table.

Please Guide me in C#.net

Upvotes: 1

Views: 11536

Answers (1)

digEmAll
digEmAll

Reputation: 57210

Basically, it depends on how you fill your ListView.

Anyway, a code like this, should work in almost every situations:

var idIdx = listView1.Columns["ID"].Index;
var codeIdx = listView1.Columns["Code"].Index;

foreach (ListViewItem item in listView1.Items)
{
    if (item.SubItems[idIdx].Text == "2")
    {
        item.SubItems[codeIdx].Text = "new value...";
        break;
    }
}

Just a caveat:

to assure the first 2 lines of this code work, you must properly initialize your columns' Name property, when you create them:

either by using the proper add overload:

listView1.Columns.Add("ID", "ID");

or by setting it later:

var col = listView1.Columns.Add("ID");
col.Name = "ID";

Upvotes: 4

Related Questions