Tuesday, September 21, 2010

Set Item selected inside listview.

I had strange issue while setting focus to list view Item. Let me share my exp with you.

I was trying to set focus on specific item of list view once list view is bound with the data. I tried with following code:

lstDetails.Items[i].Selected = true;
lstDetails.Items[i].Focused = true; 

It showed item as selected when I was in debug mode. Once I remove break point nothing was selected.

You need to write following code to item focused.
lstDetails.Items[i].Selected = true;
lstDetails.Items[i].Focused = true;
lstDetails.Items[i].EnsureVisible(); //This will set scroll position inside listview to the focused item.
lstDetails.Focus();     //This will set focus to the parent control that is listview.

Hope it will help you.

Thanks,
Ashish Chotalia

Saturday, September 18, 2010

How to hide listview column.

I would like to share some stuff with you. I come across situation where I need to hide the column for the listview control.

Earlier My approach was to set the column width for the listview with width=0 as shown below.

[ListViewName].Columns.Add("ID", 0);

It worked fine when I run the application, but the problem I found was that still user was able to change the width. To resolve that Issue I tried following thing and It worked like a charm.

Just open the form and Select ListView. Go to events grid and find "ColumnWidthChanged" event.
Create event and put the code as shown below.

private void [ListViewName]_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
{
        if (e.ColumnIndex == 0)
        {
               this.[ListViewName].Columns[e.ColumnIndex].Width = 0;
         }
}

Cheers,
Ashish Chotalia

P.S. Please replace "[ListViewName]" with your ListView Id.